C++重载(2):通过成员函数和友元函数重载

分别通过成员函数和友元函数完成重载

#include <iostream>
using namespace std;

class Complex
{
public:
	Complex(double real =0,double imag=0):real(real),imag(imag){};   //构造函数,包含有参数的和没有参数的,默认为0,0
	Complex(const Complex & p){real = p.real;imag = p.imag;}  //复制构造函数
	~Complex(){}  //析构函数
	 //以下为成员函数
	double getReal() const {return real;}
	double getImag() const {return imag;}
    void output();  //输出的函数
	Complex operator+(const Complex& p);
	//通过友元
	friend Complex operator-(const Complex &p1,const Complex &p2);
private:
	double real ,imag;
};

Complex Complex::operator+(const Complex& p) //计算加法的成员函数
{
	
	return Complex(real+p.real,imag+p.imag);
}
void Complex::output()  //输出的函数
{
	if(imag >=0)
	{
		char flag;
		flag ='+';
		cout <<real <<flag<<imag <<'i' <<endl;
	}
	else
		cout <<real <<imag <<'i' <<endl;
}

Complex operator-(const Complex &p1,const Complex &p2)
{
	return Complex(p1.real-p2.real,p1.imag - p2.imag);
}

int main()
{
	Complex a(3,4),b(4,-5),c ,d;
	cout <<"输出a=";
	a.output();
	cout <<"输出b=";
	b.output();
	cout <<"输出a+b=";
	c= a+b;
	c.output();
    cout <<"输出a-b=";
	d= a-b;
	d.output();
	return 0;
}

运行结果:

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值