我想在Line类中重载<
cout << myLineObject << endl;
但这不起作用:
class Line{
public:
float m;
float b;
string operator << (Line &line){return ("y = " + line.m + "x + " + line.b);};
};
我得到:
Invalid operands of types 'const char [5]' and 'float' to binary 'operator+'
我也尝试了
stringstream
,但出现了更多错误。正确的做法是什么?谢谢 ;)
最佳答案
operator<<
必须是一个非成员函数,因为流是左手参数。在您的情况下,由于数据成员是公共(public)的,因此可以在类外部实现:
std::ostream& operator<<(std::ostream& stream, const Line& line)
{
return stream << "y = " << line.m << " x = " << line.b;
}