運算子過載(重點++字首和字尾)
阿新 • • 發佈:2019-01-10
#include
class vector{
private:
int x,y;
public:
vector(){x=0;y=0;}
vector(int m,int n){x=m;y=n;}
~vector(){cout<<"-----"<<endl;}
void disp();
vector & operator+(vector &v);
void operator++();//字首運算子過載
vector & operator++(int);//字尾運算子過載
};
void vector::disp()
{
cout<<"(x,y)="<<"("<<x<<","<<y<<")"<<endl;
}
vector & vector::operator +(vector &v)
{
//第一種方法建立區域性物件(缺點:返回的是區域性物件)
vector temp;
temp.x=x+v.x;
temp.y=y+v.y;
return temp;
//第二中方法用呼叫物件的this指標(缺點:改變了呼叫物件的值)
}
void vector::operator ++()
{
x++;
y++;
cout<<"字首"<<endl;
}
vector & vector::operator ++(int)
{
vector temp;
temp.x=x++;
temp.y=y++;
cout<<"字尾"<<endl;
return temp;
}
int main()
{
vector A(2,3);
vector T;
A.disp();
T=A++;//字尾運算子
T.disp();
A.disp();
vector B(6,7);
B.disp();
++B;//字首運算子
B.disp();
vector C;
C=A+B;//+運算子
C.disp();
return 0;
}