在C++中重载<<运算符

nac*_*o4d 2 c++ operators

我想在Line类中重载<<运算符,所以我可以使用cout打印一个对象:

cout << myLineObject << endl;
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

class Line{
public:
    float m;
    float b;
    string operator << (Line &line){return ("y = " + line.m + "x + " + line.b);};
};
Run Code Online (Sandbox Code Playgroud)

我明白了:

Invalid operands of types 'const char [5]' and 'float' to binary 'operator+'
Run Code Online (Sandbox Code Playgroud)

我也试过,stringstream但我得到更多的错误.这样做的正确方法是什么?

谢谢 ;)

Dav*_*ley 16

列出了正确的方法,到处<<讨论重载,你已经设法错过了所有这些.

标准声明是ostream & operator<<(ostream & s, const & Line l); 它不能是成员函数,它需要返回一个引用,ostream以便您可以<<正常链接.

在您的情况下,定义将是类似的

ostream & operator<<(ostream & s, const & Line l)
{
    return s << "y = " << l.m << "x + " << l.b;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您返回传入ostream,并使用<<运算符而不是使用+运算符打印您喜欢的内容.如果你遵循这个表格,这很简单.

在这种情况下,数据成员是公共的(一般来说这不是一个好主意),因此没有访问问题.如果需要获取不可访问的值(因为它们private未在公共接口中公开),则需要将运算符声明friend为类定义中的运算符.


Mik*_*our 9

operator<<必须是非成员函数,因为流是左手参数.在您的情况下,由于数据成员是公共的,因此可以在类外部实现:

std::ostream& operator<<(std::ostream& stream, const Line& line)
{
    return stream << "y = " << line.m << " x = " << line.b;
}
Run Code Online (Sandbox Code Playgroud)