AVQ3 - int i; len=size; data= new char[len];...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <fstream> using namespace std; class String { private: char* data; int len; public: String(char *text); String(int size = 0); String(const String& a); ~String(void){ delete [] data; } String& operator = (const String& a); String& operator += (const String& a); friend int length(const String& a){ return a.len;} friend ostream& operator << (ostream& out, const String& a); friend String operator + (const String& a, const String& b); }; int main () { ofstream fout("strings.out"); String a ("My book is black"), b , c; fout << "The string a is: " << a << "\n"; b = " and white"; fout << "The length of b now is: " << length(b) << "\n"; fout << "The string b now is: " << b << "\n"; c = a + b; fout << "The string c now is: " << c << "\n"; a += b; fout << "The string a now is: " << a << "\n"; fout.close(); system("notepad strings.out"); return 0; } String::String(char *text){ int i(0); while(text[i]!='\0')i++; len=i; data= new char[len]; for(i=0;i<len;i++) data[i]=text[i]; } String::String(int size){
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int i; len=size; data= new char[len]; for(i=0;i&lt;len;i++) data[i]='0'; } String&amp; String::operator = (const String&amp; a){ if(this != &amp;a) { len = a.len; delete data; data = new char[len]; for(int i=0; i&lt;len; i++) data[i] = a.data[i]; } return (*this); } String&amp; String::operator += (const String&amp; a){ int i,j; String c; c.len=len+a.len; delete c.data; c.data=new char[c.len]; for(i=0;i&lt;len;i++) c.data[i]=data[i]; for(j=0;j&lt;a.len;j++){ c.data[i]=a.data[j]; i++; } delete data; len=c.len; data=new char [len]; for(i=0;i&lt;len;i++) data[i]=c.data[i]; delete c.data; return (*this); } ostream&amp; operator &lt;&lt; (ostream&amp; out, const String&amp; a){ int i; for(i=0;i&lt;a.len;i++) out&lt;&lt;a.data[i]; return out; } String operator + (const String&amp; a, const String&amp; b){ int i,j; String c; c.len=a.len+b.len; delete c.data; c.data= new char [c.len]; for(i=0;i&lt;a.len;i++) c.data[i]=a.data[i]; for(j=0;j&lt;b.len;j++){ c.data[i]=b.data[j]; i++; } return c; }...
View Full Document

Page1 / 2

AVQ3 - int i; len=size; data= new char[len];...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online