1. 程式人生 > >C++運算子過載(友元函式方式)

C++運算子過載(友元函式方式)

我們知道,C++中的運算子過載有兩種形式:①過載為類的成員函式(見C++運算子過載(成員函式方式)),②過載為類的友元函式。

當過載友元函式時,將沒有隱含的引數this指標。這樣,對雙目運算子,友元函式有2個引數,對單目運算子,友元函式有一個引數。但是,有些執行符不能過載為友元函式,它們是:=,(),[]和->。

過載為友元函式的運算子過載函式的定義格式如下:

friend 函式型別 operator 運算子(形參表) 
{ 
	函式體; 
} 

一、程式例項

//運算子過載:友元函式方式
#include <iostream.h>

class complex //複數類
{
public:
	complex(){ real = imag = 0;}
	complex(double r, double i)
	{
		real = r;
		imag = i;
	}
	friend complex operator + (const complex &c1, const complex &c2); //相比於成員函式方式,友元函式前面加friend,形參多一個,去掉類域
	friend complex operator - (const complex &c1, const complex &c2); //成員函式方式有隱含引數,友元函式方式無隱含引數
	friend complex operator * (const complex &c1, const complex &c2);
	friend complex operator / (const complex &c1, const complex &c2);

	friend void print(const complex &c); //友元函式

private:
	double real; //實部
	double imag; //虛部

};

complex operator + (const complex &c1, const complex &c2) 
{
	return complex(c1.real + c2.real, c1.imag + c2.imag);
}

complex operator - (const complex &c1, const complex &c2)
{
	return complex(c1.real - c2.real, c1.imag - c2.imag);
}

complex operator * (const complex &c1, const complex &c2)
{
	return complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.real + c1.imag * c2.imag);
}

complex operator / (const complex &c1, const complex &c2)
{
	return complex( (c1.real * c2.real + c1.imag * c2. imag) / (c2.real * c2.real + c2.imag * c2.imag), 
		(c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag) );
}

void print(const complex &c) 
{
	if(c.imag < 0)
		cout<<c.real<<c.imag<<'i'<<endl;
	else
		cout<<c.real<<'+'<<c.imag<<'i'<<endl;
}

int main()
{	
	complex c1(2.0, 3.5), c2(6.7, 9.8), c3;
	c3 = c1 + c2;
	cout<<"c1 + c2 = ";
	print(c3); //友元函式不是成員函式,只能採用普通函式呼叫方式,不能通過類的物件呼叫

	c3 = c1 - c2;
	cout<<"c1 - c2 = ";
	print(c3);

	c3 = c1 * c2;
	cout<<"c1 * c2 = ";
	print(c3);

	c3 = c1 / c2;
	cout<<"c1 / c2 = ";
	print(c3);
	return 0;
}

二、程式執行結果


從執行結果上我們就可以看出來,無論是通過成員函式方式還是採用友元函式方式,其實現的功能都是一樣的,都是過載運算子,擴充其功能,使之能夠應用於使用者定義型別的計算中。

三、兩種過載方式(成員函式方式與友元函式方式)的比較

一般說來,單目運算子最好被過載為成員;對雙目運算子最好被過載為友元函式,雙目運算子過載為友元函式比過載為成員函式更方便此,但是,有的雙目運算子還是過載為成員函式為好,例如,賦值運算子。因為,它如果被過載為友元函式,將會出現與賦值語義不一致的地方。