class String
{
char* array;
public:
String(const char* s)
{
array = new char[strlen(s) + 1]{ '\0' };
strcpy(array, s);
}
~String()
{
if (array)
{
delete[]array;
}
}
String operator+ (const char* p) //返回对象
{
String temp(p);
char* tempStr = temp.array;
temp.array = new char[strlen(array) + strlen(tempStr) + 1]{ '\0' };
strcpy(temp.array, array);
strcat(temp.array, p);
delete[]tempStr;
return temp;
}
friend ostream& operator<<(ostream& output, String& x); // <<函数重载只能定义成友元
};
ostream& operator << (ostream& output, String& x) //对<<重载的方式
{
output << x.array;
return output;
}
int main()
{
String string1("mystring");
cout << string1 + "ab" << endl;
cout << string1 << endl;
return 0;
}
This is my first time asking a question here, so please forgive me if there are any bad descriptions :)
Back to the point ,I have overloaded +
and <<
operators,so I want to get the output "mystringab
" by cout<<string1+"ab"<<endl
,but the output is garbled.
I think there may be a problem with the +
operator overloaded function,can someone please tell me where is the problem?
And if I want to get the correct result, how should I rewrite the overloaded function?