题目:1、先读程序,预测程序的输出结果,再运行程序验证程序的输出。用友元重载方式重新编写此程序。
我感觉原来的程序里面已经有友元重载了,就改成了如下的样子
#include <iostream>
using namespace std;
class Vector
{
public:
Vector() {}
Vector(int i, int j) { x = i; y = j; }
friend Vector operator+=(Vector v1, Vector v2)
{
v1.x += v2.x;
v1.y += v2.y;
return v1;
}
//我就改了下面这一段
/*改之前的函数
Vector operator-=(Vector v)
{
Vector temp;
temp.x=x-v.x;
temp.y=y-v.y;
return temp;
}*/
//改之后的函数
friend Vector operator-=(Vector v1,Vector v2)
{
v1.x -= v2.x;
v1.y -= v2.y;
return v1;
}
//从这里向下就没有改动了
void display()
{
cout << "(" << x << "," << y << ")" << endl;
}
private:
int x, y;
};
void main()
{
Vector v1(1, 2), v2(3, 4), v3, v4;
v3 = v1 += v2;
v4 = v1 -= v2;
cout << "v1=";
v1.display();
cout << "v2=";
v2.display();
cout << "v3=";
v3.display();
cout << "v4=";
v4.display();
}
运行结果是相同的,但好像有点太简单了,而且改动很少,似乎也没有到“重编”的程度。
请问:是我的理解错了吗?这样写可以吗?