I get a problem with my String class.
Constructor and copy constructor:
private:
char * buf;
public:
String( const char * s = "")
{
buf = strdup(s);
}
String( String &s)
: buf(strdup(s.buf))
{
}
The operator:
String operator + ( const String &s )
{
char* tmp = new char[strlen(buf) + strlen(s.buf) + 1]; // +1 for the terminating '\0'
strcpy(tmp,buf);
strcat(tmp,s.buf);
String result;
delete[] result.buf;
result.buf = tmp;
return result;
}
String operator += ( const String s )
{
delete_char_array(buf);
char* tmp = new char[strlen(buf) + strlen(s.buf) + 1];
strcpy(tmp,buf);
strcat(tmp,s.buf);
buf = strdup(tmp);
delete_char_array(tmp);
return *this;
}
void print( ostream & out )
{
char *p = buf;
out << p;
}
and I have implemented the << operator
ostream & operator << ( ostream & out, String str )
{
str.print(out);
return out;
}
My main() function is:
int main()
{
String firstString("First");
String secondString("Second");
cout << firstString + secondString << endl;
(firstString+=secondString).print(cout);
}
I can correctly get the output by the String.print(cout) but the g++ will tell me that
cout << firstString + secondString << endl;` does not have the matching
constructor for `String::String(String)`
and there are two options, 1. String::String( char * c)
and 2. String::String(String &s)
.