c/c++的运算符重载
所谓的运算符重载指的是同一个运算符完成不同的运算,运算符重载是通过运算符重载函数实现的,当c++编译遇到重载运算符时,例如c1-c2中的减法运算符-时候,会自动调用-运算符的重载函数完成减法运算。
include"iostream"
class Complex
{
float a;
float b;
public:
Complex();
~Complex();
Complex(float a1,float b1);
Complex operator+(Complex&);
friend Complex operator-(Complex &,Complex &);
void displayer();
};
Complex::Complex()
{
};
Complex::Complex(float a1,float b1)
{
a=a1;
b=b1;
}
Complex::~Complex()
{
}
Complex Complex::operator+ (Complex &c)
{
static Complex temp;
temp.a=c.a+a;
temp.b=c.b+b;
return temp;
}
Complex operator -(Complex &c1,Complex &c2)
{
static Complex temp;
temp.a=c1.a-c2.a;
temp.b=c1.b-c2.b;
return temp;
}
void Complex::displayer()
{
std::cout<<"a: "<<a<<" b: "<<b<<std::endl;
}
int main()
{
Complex c1(1,2),c2(3,4),c3,c4;
std::cout<<"c1"<<std::endl;
c1.displayer();
std::cout<<"c2"<<std::endl;
c2.displayer();
c3=c1-c2;
std::cout<<"c1-c2"<<std::endl;
c3.displayer();
std::cout<<"c1"<<std::endl;
c1.displayer();
std::cout<<"c2"<<std::endl;
c2.displayer();
c4=c1+c2;
std::cout<<"c1+c2"<<std::endl;
c4.displayer();
system("pause");
}
运行截图: