在 cpp 中重载<<运算符时出错?不知道为什么?

Error in overloading << operator in cpp ? dont know why?

本文关键字:lt cpp 不知道 为什么 出错 运算符 重载      更新时间:2023-10-16

这是我的完整代码,除了<<重载之外,一切都很好。有人能告诉我为什么>>工作正常时会产生错误吗?任何帮助都将不胜感激。

error"请参阅声明<<"

#include<iostream>
#include<conio.h>
using namespace std;
class point
{
private:
    int x,y;
public:
point(int x=0, int y=0)
{
    this->x = x;
    this->y = y;
}
point & operator + (const point &obj)
{
    point temp;
    temp.x = this->x + obj.x;
    temp.y = this->y + obj.y;
    return temp;
}
point & operator - (const point &obj)
{
    point temp;
    temp.x = this->x - obj.x;
    temp.y = this->y - obj.y;
    return temp;
}
friend point & operator >>(istream in, point obj);
friend point & operator <<(ostream out, point obj);
};
void main()
{
    _getch();
}
point & ::operator >> (istream in, point obj)
{
    in >> obj.x;
    in >> obj.y;
    return obj;
}
point & ::operator << (istream out, point obj)    // <--- Here is the Problem
{
    //out << "( " << obj.x << " , " << obj.y << " )";
    return obj;
}

您应该始终返回流引用,而不是点引用。

更新:我认为其他人在评论中指出了实际问题(istream而不是ostream)。此外,您通过值而不是通过引用来传递流。以下是您的代码应该是什么样子:

istream& ::operator >> (istream &in, const point &obj)
{
    in >> obj.x;
    in >> obj.y;
    return in;
}
ostream& ::operator << (ostream &out, const point &obj)    // <--- Here is the Problem
{
    out << "( " << obj.x << " , " << obj.y << " )";
    return out;
}

更新到我的更新:我还想说,点值应该作为常量引用传递,否则你永远无法传递常量点值(假设你想传递)。请参阅我上面的编辑。

还有一点(并非真正相关):除非迫不得已,否则尽量不要让他们成为Point的朋友。x和y值似乎需要在某个时候公开。如果他们可以公开访问,那么运营商就没有理由成为朋友。

函数被声明为接受ostream,但被定义为接受istream。这就是错误。

然而,这里有几个问题。

  • 您应该通过引用获取流对象,否则您使用的是副本,它们甚至可能无法复制
  • 您应该返回对流对象的引用,以允许使用链接运算符

建议过载采用以下形式:

ostream& operator<<(ostream& os, const point& p)
{
    os << "(" << p.x << "," << p.y << ")";
    return os;
}

你现在可以做以下事情:

point x;
point y;
// ...
std::cout << x << " and " << y << "n";