[英]Overloading << operator for my own class why is this not working?
我有一個 class 並且我想重載其中的 << 運算符:
class Vector3
{
int x;
int y;
int z;
public:
Vector3(int a, int b, int c) : x{a}, y{b}, z{c} {}
Vector3 operator+(const Vector3& v);
friend std::ostream& operator<<(std::ostream& ost, const Vector3& v);
};
但基本上我希望能夠訪問數據成員,所以在這里我和朋友 function 一起做了,只是在不同的文件中定義了 function:
std::ostream& operator<<(std::ostream& ost, const Vector3& v)
{
return ost << '(' << v.x << ',' << v.y << ',' << v.z << ')';
}
但是我的問題是,當我不使用朋友 function 而只是像這樣聲明 function 時,怎么會這樣:
std::ostream& operator<<(std::ostream& ost);
然后在不同的文件中定義它:
std::ostream& Vector3::operator<<(std::ostream& ost)
{
return ost << '(' << x << ',' << y << ',' << z << ')';
}
當我嘗試實際使用它時
int main()
{
Vector3 u(2,4,3);
std::cout << u;
}
它只是說:
> no operator matches these operands operand types are:
> std::ostream << Vector3
但是如果我這樣做u.operator<<(std::cout);
那么它有效嗎? 但為什么? 我以為std::cout << u;
與u.operator<<(std::cout)
基本相同;
A a;
B b;
a << b;
編譯器在此處查找A
中的成員operator<<
,即如果A::operator(B const&)
存在,則上面截取的代碼使用它,但不考慮B::operator<<(A&)
。
對於您的代碼,這意味着所需的成員運算符是您無法添加的std::ostream::operator<<(Vector3 const&)
,因為std::ostream
是在標准庫中定義的。 您在這里唯一的選擇是免費的 function。
訂單很重要。 您提供的重載定義u << cout
而不是cout << u
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.