c++ - 如何在自己的班级中重载“+”和“<<”运算符
问题描述
我创建了“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;
}
解决方案
表达方式
(p1+p2)
是一个右值。功能
ostream& operator <<(ostream &out, Point &p)
期望引用Point
. 您不能将右值传递给此函数。将其更改为
ostream& operator <<(ostream &out, const Point &p)
在声明和定义中。
推荐阅读
- javascript - 如何使用 Typescript 键入 __proto__ 上的函数
- javascript - js回文任务的递归
- python - Selenium(PYTHON) 语法难题
- java - 没有从字符串值反序列化的字符串参数构造函数/工厂方法->java.util.ArrayList[0]
- excel-formula - 条件格式问题
- swiftui - Swiftui,按钮网格视图
- javascript - 如何正确对齐元素>
- c++ - 英特尔编译器内联大小
- c++ - 如何使用 stable_sort 对fruit_name(文件中的数据)进行排序并打印
- ios - OpenTok iOS SDK 2.18.1 屏幕共享质量问题