繁体   English   中英

为我自己的 class 重载 << 运算符,为什么这不起作用?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM