C++操作符重载实例,我们把坐标值CVector的加法进行重载,计算c3=c1+c2时,也就是计算x3=x1+x2,y3=y1+y2,以下是C++代码:
#include <iostream>
using namespace std;
class CVector{
public:
int x,y;
CVector(){} ; //定义语句后面的分号可加可不加,本句是加了分号,OK
CVector(int a, int b):x(a),y(b){} //定义语句后面不加分号,OK
CVector operator+(CVector&); //声明语句后面的分号必须加上
};
CVector CVector::operator+(CVector& para){
CVector temp; //此处使用默认构造器
// temp.x = x + para->x; //error: base operand of '->' has non-pointer type 'CVector'
temp.x = x + para.x;
temp.y = y + para.y;
return temp;
}
int main(){
CVector c1(3, 5);
CVector c2(4, 6);
CVector res = c1+c2;
cout << "res.x=" << res.x << endl;
cout << "res.y=" << res.y << endl;
return 0;
}