c++知识点----友元函数重载运算符

来源:互联网 发布:深圳网络推广招聘 编辑:程序博客网 时间:2024/06/05 12:42

定义一个类complex,含private变量:double real与imag,并定义构造函数初始化这两个变量。用友元函数重载运算符“+”,使两个对象real相加,imag相加。输出相加后的对象的值加以验证


使用到的文件

main.cpp

#include <iostream>using namespace std;#include "class.h"int main(){complex c1(2.5, 3.7), c2(4.2, 6.5);complex c3 = c1 + c2;c3.show();system("pause");//暂停return 0;}

class.h

#pragma onceclass complex{public:complex(double,double);//初始化void show();//输出私有变量friend complex operator+(const complex &c1,const complex &c2);//友元函数运算符重载private:double real, imag;};inline complex::complex(double r1, double i2)//友元函数运算符重载{real = r1;imag = i2;}inline void complex::show(){cout << '(' << real << ',' << imag << ')' << endl;}complex operator+(const complex & c1, const complex & c2){complex c3(0,0);c3.real = c1.real + c2.real;c3.imag = c1.imag + c2.imag;return c3;}




原创粉丝点击