【问题标题】:How to overload the '+' and '<<' operator in myself class如何在自己的班级中重载“+”和“<<”运算符
【发布时间】:2019-10-14 04:24:23
【问题描述】:

我创建了“Point”类,在 2 Point 对象和运算符“

 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;
    }

【问题讨论】:

  • 错误是什么?
  • 没有匹配的运算符“
  • 出现在这个"cout
  • 不要评论。编辑您的问题并添加确切的错误消息。
  • FULL 错误,请。这可能是由于您的班级忽略了 const-correctness

标签: c++


【解决方案1】:

表达式

(p1+p2)

是一个右值。功能

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

期望引用Point。您不能将右值传递给此函数。改成

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

在声明和定义中。

【讨论】:

  • 请注意,应该对运算符定义和朋友声明进行更新。 (对于 OP,不是你。)
  • 如果我想让“cout
  • @dongdong 阅读我回答的最后一行
  • getX 和 getY const 也是需要的
【解决方案2】:

C++ 只允许将临时值传递给 const 引用。看到这个:How come a non-const reference cannot bind to a temporary object?

修改一个临时的是没有意义的。你需要定义一个 const 引用来保证你不会修改它并延长它的生命周期。

【讨论】:

    【解决方案3】:

    重载运算符时,const 正确性不是可选的。以下原型是您所需要的......

            Point operator + (const Point &p) const;
            friend ostream& operator <<(ostream& out, const Point &p);
    

    【讨论】:

    • 你为什么这么认为?这是编译器扩展吗?你有 operator+ 中所需常量的参考吗?wandbox.org/permlink/72yCgKftGGHVEIsi
    • 好的,因此您建议在将来可能的特殊情况下使用它,但在当前问题的示例中,它不是必需的,是吗?甚至可以改变论点。当然,在这种情况下你不能传递右值。
    • Point operator + (Point &amp;p) { ++p._x; ++_x; return *this; } 有效但不推荐。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多