2
#include<iostream>
using namespace std;
class aClass
{
public:
char *message;
aClass(const char *message);
~aClass(){delete[] message;}
};
aClass::aClass(const char* newmessage)
{
message = new char[strlen(newmessage) +1];
strcpy(message,newmessage);
}
const ostream& operator<<(const ostream& o, const aClass &a)
{
o << a.message;
return o;
}
int main()
{
aClass b("Hello");
cout << b;
}
有人可以向我解釋爲什麼上面的代碼產生無限循環嗎?超載時出現堆棧溢出<<運算符
爲什麼不直接使用'的std :: string`? – 2011-01-08 22:11:17
請注意,您違反了[三條規則](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29)。如果我複製你的課堂,繁榮。你還需要一個拷貝構造函數和賦值操作符,使用[copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)。請注意,您應該只是使用`std :: vector`或`std :: string`。 –
GManNickG
2011-01-08 22:11:45