#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;
}
Can someone expla开发者_JAVA百科in to me why the code above produces an infinite loop?
Because you have const
where it shouldn't be:
///// /////
const ostream& operator<<(const ostream& o, const aClass &a)
The output stream is suppose to be non-const; after all, outputting data is changing something. So when you do this:
o << a.message;
It cannot use the normal overload for char*
, because that one operates on a non-const stream. Instead, it searches for an appropriate overload and finds yours, determines it can construct an aClass
from a.message
(because your constructor is not explicit
), does so, and calls it. This repeats forever.
It should be written as:
ostream& operator<<(ostream& o, const aClass &a)
{
o << a.message;
return o;
}
精彩评论