1. 程式人生 > >C++過載(2):通過成員函式和友元函式過載

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

執行結果: