在代码15行处,为什么必须要返回引用,若不返回引用第39行会报错
#include<iostream>
#include<math.h>
using namespace std;
class Point {
public:
Point() {
}
Point(int a, int b) {
x = a;
y = b;
}
int x, y;
double r;
Point& operator+(int a) {
this->x = this->x + a;
this->y = this->y + a;
return *this;
}
double operator + (Point & p) {
r = sqrt((p.x - this->x) * (p.x - this->x) + (p.y - this->y) * (p.y - this->y));
return r;
}
private:
};
ostream &operator<<(ostream& cout, Point& p) {
cout << "[" << p.x << "," << p.y << "]";
return cout;
}
int main() {
int x, y;
cin >> x >> y;
Point p1(x, y);
cin >> x >> y;
Point p2(x, y);
cout << "Distance between p1" << p1 << " and p2" << p2 << " is " << p1 + p2 << endl;
cout << p1 + 3 << " " << p2 + 5 << endl;
return 0;
}
用引用是错误的
例如
point t1,t2,t3;
t1=
t2=
t3=t1+t2; 你用引用则t1+t2之后,t1也发生改变
至于你39行出错,operator<<参数应该是const point& ,p2+5将返回一个临时值,如果operator<< 的参数是引用,不能绑定临时变量,要const point& 才可以