类重载格式: 函数类型 operator 运算符名称(形参表)型参数=使用参数-1
使用+号实现复数相加(不使用类重载):
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real = 0;
imag = 0;
}
Complex(double r, double i)
{
real = r;
imag = i;
}
Complex Complex_add(Complex &c);
void display();
private:
double real;
double imag;
};
Complex Complex::Complex_add(Complex &c)
{
Complex c1;
c1.real = real + c.real;
c1.imag = imag + c.imag;
return c1;
}
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex c1(5, 10), c2(10, 5), c3;
c3 = c1.Complex_add(c2);
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c1+c2="; c3.display();
while (1);
return 0;
}
使用类重载:
#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 &c);//在此进行类重载运算符“+”
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c)//定义类重载运算符“+”的函数
{
Complex c1;
c1.real = real + c.real;
c1.imag = imag + c.imag;
return c1;
}
void Complex::display()
{
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
Complex c1(5, 10), c2(10, 5), c3;
c3 = c1+c2;//也可以用 c3=c1.operator(t2)
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << "c1+c2="; c3.display();
while (1);
return 0;
}