#include <iostream>
using namespace std;//运算符的重载
class A
{
public:
A(int x)
{
a = x;
}
~A()
{
}
//运算符重载函数+=;加法
A operator +=(const A&b)
{
this->a = this->a+ b.a;
return this->a;
}
A operator -=(const A&b)
{
//运算符重载函数-=;减法
this->a = this->a- b.a;
return this->a;
}
A operator *=(const A&b)
{
//运算符重载函数*=;乘法
this->a = this->a* b.a;
return this->a;
}
A operator /=(const A&b)
{
//运算符重载函数/=;除法
this->a = this->a/ b.a;
return this->a;
}
int a;
};
void main()
{
A a(1);
A b(2);
A c(3);
A d(4);
A e(5);
b += a;//现在才可以编译通过,进行加减乘除运算
c -= a;
d *= a;
e /= a;
cout<<"运算符重载加法结果是:"<<b.a<<endl;
cout<<"运算符重载减法结果是:"<<c.a<<endl;
cout<<"运算符重载乘法结果是:"<<d.a<<endl;
cout<<"运算符重载除法结果是:"<<e.a<<endl;
}
使用重载函数:
A operator +=(const A&b)
{
this->a = this->a+ b.a;
return this->a;
}