复数的乘法(通过运算符重载实现)
#include<iostream>
#include<conio.h>
using namespace std;
class Complex {
public:double real;
double imag;
Complex(double r = 0, double i = 0)
{
real = r;
imag = i;
}
void print();
friend Complex operator*(Complex co1, Complex co2);
};
Complex operator*(Complex co1, Complex co2)
{
Complex temp;
temp.real = (co1.real * co2.real)-(co1.imag * co2.imag);
temp.imag = (co1.imag * co2.real)+(co1.real * co2.imag);
return temp;
}
void Complex::print()
{
cout << "total real=" << real << "" << "total imag=" << imag << endl;
}
int main()
{
Complex com1(1.1, 2.2), com2(3.3, 4.4), total1;
total1 = com1 * com2;
total1.print();
_getch();
return 0;
}
总结:运算符重载函数有三种实现方式,分别是类外定义运算符重载函数,友元运算符重载函数以及将运算符重载函数作为类的成员函数。我选择的是用友元重载函数实现运算符重载,进而实现复数的乘法。总的来看,类外定义重载函数,只能访问类中公有成员,而无法访问其私有及保护成员。友元函数定义和类中将运算符重载作为成员函数声明,类外定义的方法则可以解决这个问题。但在复杂问题中,对于友元函数的使用要谨慎,使用不当会影响类的封装性。
