C++用顶层函数重载操作符(一)

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


前面章节中,我们已经学会了将操作符重载函数声明为类的成员函数。除此之外,还可以将操作符重载函数声明为顶层函数。

学习将操作符重载函数声明为类成员函数时,我们不断强调二元操作符的函数参数为一个,一元操作符重载函数不需要函数参数。如果以顶层函数的形式重载操作符时,二元操作符重载函数必须有两个参数,一元操作符重载必须有一个参数。

将操作符重载函数声明为顶层函数时,必须至少有一个类对象参数,否则编译器无法区分操作符是系统内建的还是程序设计人员自己定义的,有了一个类对象参数之后,系统则会根据情况调用内建或自定的操作符。

#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.getreal()*B.getimag()+A.getimag()+B.getreal());
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(1.0,2.0);
complex c2(3.0, 4.0);
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+6i
c1 - c2 = -2+-2i
c1 * c2 = -5+9i
c1 / c2 = 0.44+0.08i