- 定义一个复数类,用友元函数实现对双目运算符“+”的运算符重载,使其 适用于复数运算。
#include<iostream>
using namespace std;
class plural
{
private:
float real_part;
float imag;
public:
plural();
plural(float rp,float im);
friend plural operator+(const plural &P,const plural &Q);
void showPlural();
};
plural::plural():real_part(0.0),imag(0.0){}
plural::plural(float rp,float im):real_part(rp),imag(im){}
plural operator+(const plural &P,const plural &Q){
plural temp;
temp.real_part = Q.real_part + P.real_part;
temp.imag = Q.imag + P.imag;
return temp;
}
void plural::showPlural(){
cout<<real_part<<" + "<<imag<<"i"<<endl;
}
int main(){
plural A(2.1,5.6);
plural B(3.4,-1.2);
plural C;
C = A + B;
C.showPlural();
return 0;
}