c ++运算符<<重载

Gam*_*aca -2 c++ operator-overloading visual-studio-2013

我是C++的初学者,我有以下问题.当我在VS2013中运行以下代码时,出现错误.

class Y{
public:
    Y(int un_x, int un_y) 
    : x_(un_x), y_(un_y) {}

    int x() const {
        return x_;
    }
    int y() const {
        return y_;
    }
private:
    int x_;
    int y_;
};
class X{
    private:
       Y coord;
    public:
    // some code ...

        Y position() const {
           return coord;
        }

       void display(ostream& output) const {
            output << "The object is in position " << position();
       }
};




ostream& operator<<(ostream& output, Y x){
     output<< "(" << x.x() << ", " << x.y() << ")" << endl;
     return output;
}
Run Code Online (Sandbox Code Playgroud)

如果我创建了一个类X的对象some_object并尝试:

cout << some_object ;
Run Code Online (Sandbox Code Playgroud)

我收到了以下错误:

 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Y' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

Nik*_*lis 7

您尝试使用它之后是否<<定义了运算符- 即在函数之后?如果是这样,您将需要移动它以便在使用之前定义它,或者至少声明它(即,为它提供原型):display()

ostream& operator<<(ostream &output, Y x);
Run Code Online (Sandbox Code Playgroud)

作为旁注,您应该通过Y常量引用而不是值传递实例:

ostream& operator<<(ostream& output, Y const& x);
Run Code Online (Sandbox Code Playgroud)