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

版权声明:中国地质大学(北京)地球物理与信息技术学院 E_Mail:[email protected] https://blog.csdn.net/haoaoweitt/article/details/81456533

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

#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;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/haoaoweitt/article/details/81456533