#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;
}
本文详细介绍了C++中运算符重载的实现方法,包括前缀和后缀运算符重载,以及如何使用运算符重载来增强代码的可读性和实用性。
&spm=1001.2101.3001.5002&articleId=16880207&d=1&t=3&u=337b07913be54319b320d050e07578fc)
1149

被折叠的 条评论
为什么被折叠?



