首页 > 解决方案 > 如何在自己的班级中重载“+”和“<<”运算符

问题描述

我创建了“Point”类,在 2 Point 对象和运算符“<<”之间重载运算符“+”以显示 Point 对象。我无法编译和运行代码。错误是没有匹配的运算符“<<”。这发生在 "cout << "p3: " << (p1+p2) << endl;"

 class Point {
    public:
        Point(int x=0, int y=0) : _x(x), _y(y) {};
        Point operator +(Point &p);
        int getX() {
            return _x;
        }
        int getY() {
            return _y;
        }
        friend ostream& operator <<(ostream& out, Point &p);
    private:
        int _x, _y;
    };

    Point Point::operator +(Point &p) {
        Point np(this->_x+p.getX(), this->_y+p.getY());
        return np;
    }

    ostream& operator <<(ostream &out, Point &p) {
        out << '(' << p._x << ',' << p._y << ')';
        return out;
    }

    int main() {
        Point p1(1, 2);
        Point p2;
        cout << "p1: " << p1 << endl;
        cout << "p2: " << p2 << endl;
        cout << "p3: " << (p1+p2) << endl;
        system("pause");
        return 0;
    }

标签: c++

解决方案


表达方式

(p1+p2)

是一个右值。功能

ostream& operator <<(ostream &out, Point &p)

期望引用Point. 您不能将右值传递给此函数。将其更改为

ostream& operator <<(ostream &out, const Point &p)

在声明和定义中。


推荐阅读