C++双目运算符友元函数解答

img


//课堂练习1:
//分别应用friend友元函数和类的成员函数
//设计重载双目运算符+的运算符重载函数operator+()
//实现类对象相加com1+com2,
#include
using namespace std;
class complex{
private: double real, imag;
public:
complex(double r=0,double i=0){ real=r;imag=i; }
void print();
//1 声明运算符重载函数operator+()
};
void complex::print()
{ cout<<"real="<<real<<" imag="<<imag<<endl; }
//2 定义运算符重载函数operator+()

int main()
{ complex com1(1.1,2.2),com2(3.3,4.4),total1,total2;
total1= //3 显式调用operator+()函数
total1.print();
total2= //4 隐式调用operator+()函数
total1.print();
return 0;
}