C++中的重载<<出错

Error Overloading << in C++

本文关键字:lt 出错 重载 C++      更新时间:2023-10-16

,所以我试图超载&lt;&lt;操作员。我在标题文件中定义了如下:

&operator<<(std::ostream &o, const gVector3 &v)

我已经在CPP文件中定义了它:

std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){
   return o << "The vector elements are" << v[0] << v[1] << v[2];
}

我会收到以下错误消息。有人知道为什么吗?

C:QtToolsQtCreatorbinHomework1gVector3.cpp:112: error: 'std::ostream& gVector3::operator<<(std::ostream&,
const gVector3&)' must take exactly one argument
std::ostream &gVector3::operator<<(std::ostream &o, const gVector3 &v){

您的帮助非常感谢! ^

您已将声明放在类定义中,对于编译器而言,这意味着它是成员函数 - 运算符,因为类成员只能采用一个参数。另一个参数是您要调用的对象。更轻松理解的示例:

struct Foo {
    void operator<<(int) { }
};
int main()
{
    Foo f;
    f << 5;
    // can be also called like this:
    f.operator<<(5);
}

您需要的是friend指示符,以告诉编译器您要声明一个非会员:

friend std::ostream& operator<<(std::ostream &o, const gVector3 &v)

这次是非会员的另一个示例:

struct Foo {
    friend void operator<<(Foo, int) { }
};
int main()
{
    Foo f;
    f << 5;
    // this time, it can be called like this:
    operator<<(f, 5);
}

这是假设操作员需要访问gVector3的私人数据。如果没有,请删除friend并在课堂外声明。