[英]Overloading << operator for my own class why is this not working?
I have a class and I wanna overload the << operator in it:我有一个 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);
};
But basically I want to be able to access the data members so here I did it with a friend function and just defined the function in a different file:但基本上我希望能够访问数据成员,所以在这里我和朋友 function 一起做了,只是在不同的文件中定义了 function:
std::ostream& operator<<(std::ostream& ost, const Vector3& v)
{
return ost << '(' << v.x << ',' << v.y << ',' << v.z << ')';
}
But my question is how come when I don't use a friend function and just declare the function like this:但是我的问题是,当我不使用朋友 function 而只是像这样声明 function 时,怎么会这样:
std::ostream& operator<<(std::ostream& ost);
Then define it in a different file:然后在不同的文件中定义它:
std::ostream& Vector3::operator<<(std::ostream& ost)
{
return ost << '(' << x << ',' << y << ',' << z << ')';
}
When I try to actually use it当我尝试实际使用它时
int main()
{
Vector3 u(2,4,3);
std::cout << u;
}
It just says:它只是说:
> no operator matches these operands operand types are:
> std::ostream << Vector3
But if I do u.operator<<(std::cout);
但是如果我这样做u.operator<<(std::cout);
Then it works?那么它有效吗? But why?但为什么? I thought that std::cout << u;
我以为std::cout << u;
is basically the same as u.operator<<(std::cout)
;与u.operator<<(std::cout)
基本相同;
A a;
B b;
a << b;
The compiler looks for the member operator<<
in A
here, ie if A::operator(B const&)
exists, the code snipped above uses it, but B::operator<<(A&)
is not considered.编译器在此处查找A
中的成员operator<<
,即如果A::operator(B const&)
存在,则上面截取的代码使用它,但不考虑B::operator<<(A&)
。
For your code this means the member operator required is std::ostream::operator<<(Vector3 const&)
which you cannot add, since std::ostream
is defined in the standard library.对于您的代码,这意味着所需的成员运算符是您无法添加的std::ostream::operator<<(Vector3 const&)
,因为std::ostream
是在标准库中定义的。 Your only choice here is a free function.您在这里唯一的选择是免费的 function。
Order matters.订单很重要。 The overload you provided defines u << cout
and not cout << u
.您提供的重载定义u << cout
而不是cout << u
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.