C++用顶层函数重载操作符(二) 顶层函数的优势

时间:2023-01-16 08:55:56


#include <iostream>
using namespace std;
class complex
{
public:
complex();
complex(double a);
complex(double a, double b);
double getreal() const { return real; }
double getimag() const { return imag; }
void setreal(double a){ real = a; }
void setimag(double b){ imag = 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.setreal(A.getreal() + B.getreal());
C.setimag(A.getimag() + B.getimag());
return C;
}
//重载减法操作符
complex operator-(const complex & A, const complex &B)
{
complex C;
C.setreal(A.getreal() - B.getreal());
C.setimag(A.getimag() - B.getimag());
return C;
}
//重载乘法操作符
complex operator*(const complex & A, const complex &B)
{
complex C;
C.setreal(A.getreal() * B.getreal() - A.getimag() * B.getimag() );
C.setimag(A.getimag() * B.getreal() + A.getreal() * B.getimag() );
return C;
}
//重载除法操作符
complex operator/(const complex & A, const complex & B)
{
complex C;
double square = B.getreal() * B.getreal() + B.getimag() * B.getimag();
C.setreal((A.getreal() * B.getreal() + A.getimag() * B.getimag())/square);
C.setimag((A.getimag() * B.getreal() - A.getreal() * B.getimag())/square);
return C;
}
int main()
{
complex c1,c3, c2(15.5, 23.1);
c1 = c2 + 13.5;

c1.display();
cout<<endl;
c1 = 13.5 + c2;
c1.display();
cout<<endl;

c3=c2/2;
c3.display();
cout<<endl;

c3=c2*2;
c3.display();
cout<<endl;
return 0;
}
29 + 23.1 i 
29 + 23.1 i
7.75 + 11.55 i
31 + 46.2 i

这个例子是以顶层函数的形式定义操作符重载函数。我们同样来看主函数,其中定义了 c1 和 c2 两个 complex 类对象。先来看一下语句c1 = c2 + 13.5;,这个语句可以理解如下:

c1 = operator+(c2, 13.5);

因为我们在顶层函数中定义了complex operator+(const complex & A, const complex &B)函数,系统在执行c1 = operator+(c2, 13.5);时找到了对应的顶层函数,虽然参数不对,但可以通过类的构造函数将 13.5 转换成 complex 类对象,如此就满足 operator+() 函数的调用条件了,故而这一句是没有问题的

我们再来看一下语句c1 = 13.5 + c2;,这一语句可以理解为:

c1 = operator+(13.5, c2);

这一句的执行与c1 = operator+(c2, 13.5);是一样的,它可以利用类的构造函数将 13.5 转换为 complex 类对象,因此这一句也是可以正确执行的。

我们不难体会出以顶层函数形式重载操作符的优势。总结一下,以类成员函数的形式进行操作符重载,操作符左侧的操作数必须为类对象;而以顶层函数的形式进行操作符重载,只要类中定义了相应的转型构造函数,操作符左侧或右侧的操作数均可以不是类对象,但其中必须至少有一个类对象,否则调用的就是系统内建的操作符而非自己定义的操作符重载函数了。