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

定义一个类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 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;
}




  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值