我们以顶层函数的形式进行操作符重载,但是因为无法直接访问 complex 类中的私有成员,故而在类中增添了 getimag()、getreal()、setimag() 和 setreal() 函数以操作类中的私有成员变量,如此一来实现这些操作符重载函数看上去就有些复杂了,不是那么直观。除了此种方法以外,我们还可以将 complex 类中的私有成员 real 和 imag 声明为 public 属性,但如此一来就有悖类的信息隐藏机制了。除了这两种方法外,我们是否还有其它方法解决这个问题呢
答案是肯定的,还有一种方法,前面章节我们介绍过友元函数,如果我们将操作符重载函数这些顶层函数声明为类的友元函数,那么就可以直接访问类的私有成员变量了。
using namespace std;
class complex
{
public:
complex();
complex(double a);
complex(double a, double b);
friend complex operator+(const complex & A, const complex & B);
friend complex operator-(const complex & A, const complex & B);
friend complex operator*(const complex & A, const complex & B);
friend complex operator/(const complex & A, const complex & B);
void display()const;
private:
double real; //复数的实部
double imag; //复数的虚部
};
complex::complex()
{
real = 0.0;
imag = 0.0;
}
complex::complex(double a)
{
real = a;
imag = 0.0;
}
complex::complex(double a, double b)
{
real = a;
imag = b;
}
//打印复数
void complex::display()const
{
cout<<real<<" + "<<imag<<" i ";
}
//重载加法操作符
complex operator+(const complex & A, const complex &B)
{
complex C;
C.real = A.real + B.real;
C.imag = A.imag + B.imag;
return C;
}
//重载减法操作符
complex operator-(const complex & A, const complex &B)
{
complex C;
C.real = A.real - B.real;
C.imag = A.imag - B.imag;
return C;
}
//重载乘法操作符
complex operator*(const complex & A, const complex &B)
{
complex C;
C.real = A.real * B.real - A.imag * B.imag;
C.imag = A.imag * B.real + A.real * B.imag;
return C;
}
//重载除法操作符
complex operator/(const complex & A, const complex & B)
{
complex C;
double square = B.real * B.real + B.imag * B.imag;
C.real = (A.real * B.real + A.imag * B.imag)/square;
C.imag = (A.imag * B.real - A.real * B.imag)/square;
return C;
}
int main()
{
complex c1(3, 4);
complex c2(1, 2);
complex c3;
c3 = c1 + c2;
cout<<"c1 + c2 = ";
c3.display();
cout<<endl;
c3 = c1 - c2;
cout<<"c1 - c2 = ";
c3.display();
cout<<endl;
c3 = c1 * c2;
cout<<"c1 * c2 = ";
c3.display();
cout<<endl;
c3 = c1 / c2;
cout<<"c1 / c2 = ";
c3.display();
cout<<endl;
return 0;
}
c1 + c2 = 4 + 6 i
c1 - c2 = 2 + 2 i
c1 * c2 = -5 + 10 i
c1 / c2 = 2.2 + -0.4 i
|