我是C++的初學者,我有以下問題。 當我在VS2013中運行以下代碼時,出現錯誤。C++ operator <<重載
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;
}
如果我創建類X的對象some_object並儘量做到:
cout << some_object ;
我得到followng錯誤:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Y' (or there is no acceptable conversion)
您無法運行該代碼,因爲沒有實際的代碼可以運行(如主功能)。如果你的意思是你在代碼下面提到的內容,那麼輸出'X'不會超載。 – chris
上面鏈接的代碼由MooingDuck編譯並在VS2013下正確運行。請發佈重現問題的[SSCCE](http://sscce.org)。 – Praetorian
另外,'X'與這個問題有什麼關係? –