C++--重载(非成员函数):复数加减法

测试代码

#include<iostream>
#include<string>
using std::ostream;
using std::cin;
using std::cout;
using std::endl;
class complex{

public:
	complex(double a=0.0,double b=0.0):a(a),b(b){
     cout<<"构造函数被调用!"<<endl;
	}
	~complex(){
	
		cout<<"析构函数被调用!"<<endl;
	}
	friend complex operator + (const complex &c1,const complex &c2)
	{
		return complex((c1.a+c2.a),(c1.b+c2.b));
	}
		friend complex operator - (const complex &c1,const complex &c2)
	{
		return complex((c1.a-c2.a),(c1.b-c2.b));
	}


		friend ostream & operator << (ostream &out ,const complex &c)
		{
			out<<"("<<c.a<<","<<c.b<<")"<<endl;
			return out;
		}

private:
	double a;
	double b;
};
int main()
{
	complex a1(2,2);
	complex a2(4,4);
	complex a3;
a3=a1+a2;
cout<<a3;
	return 0;
}

程序运行界面

在这里插入图片描述

发布了218 篇原创文章 · 获赞 523 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/weixin_44225182/article/details/105370834
今日推荐