I'm from a C/Java background, new-ish to C++, and I came across a problem with operator overloading (I think) that rather puzzled me.
The basic plan is simple - a class with a string that can have bits appended to it throughout its life (as well as doing other things).
Things all go dandy when I give my string at construction-time, but when I use the default constructor, I get a weird error message. The following code snippet is a boiled-down version of my problem (but still complete & compilable):
Code:
#include <string>
#include <sstream>
using namespace std;
class A
{
public:
A(void) : msg() { }
A(string str) : msg(str) { }
string msg;
friend A& operator<<(A& a, string str);
};
A& operator<<(A& a, string str)
{
stringstream ss (a.msg);
ss << str;
a.msg.assign(ss.str());
return a;
}
int main(void)
{
//A a(); // <- gives an error...?
A a("cake");
a << "cake";
}
When I compile as it is above, I get no warnings. When I compile with the 'A a();' line uncommented, and the 'A a("cake")' commented, I get the following error:
Code:
a.cpp: In function ‘int main()’:
a.cpp:29: error: invalid operands of types ‘A()’ and ‘const char [5]’ to binary ‘operator<<’
What's going on here? The types involved in 'a << "cake"' are
valid when I use the string-accepting constructor, but
invalid when I use the default constructor.
I'd be grateful if anyone has any ideas...???
John G
P.S. I'm using g++ version 4.4.1 on Ubuntu 9.10, if it makes any difference.