用运算符重载函数作为类成员函数的方法重载运算符+
下面的例子来自于课本:
#include <iostream>
using namespace std;
class Complex
{
public:
Complex() //无参构造函数
{
real = 0;
imag = 0;
}
Complex(double r, double i) //有参构造函数
{
real = r;
imag = i;
}
Complex operator + (Complex &c2); //声明重载运算符
void display(); //成员函数,对类中的变量进行输出
private:
double real;
double imag;
};
Complex Complex::operator +(Complex &c2)
{
Complex C;
C.real = real + c2.real;
C.imag = imag + c2.imag;
return C;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl; //输出复数形式
}
int main()
{
Complex c1(3,4), c2(5,-10), c3;
c3 = c1 + c2; //运算符+ 用于复数运算
cout<<"c1= ";
c1.display();
cout<<"c2= ";
c2.display();
cout<<"c1+c2= ";
c3.display();
return 0;
}
主函数中执行c1+c2语句,是调用了运算符重载函数operator +;
相当于c1.operator + ( );
运行结果为: