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

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


c++知识点----友元函数重载运算符_第1张图片使用到的文件

main.cpp

#include 
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 once
class 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;
}




你可能感兴趣的:(c++综合运用)