天天看點

C++ 虛函數與友元函數的配合

虛函數與友元函數的配合

虛函數具有動态聯編性,在類族中有強大功能;友元函數具有跨類通路的功能,但不能繼承。

二者若能巧妙結合,會同時發揮各自的功能。

/*
虛函數與友元函數的配合
注意:VC++6.0 不支援友元 ,VS支援
*/
#include <iostream>
using namespace std;

class Base
{
public:
	Base(){x=0;}
	Base(int xx){x=xx;}
	virtual void print(ostream &output)=0;
	int GetX();
private:
	int x;
};
void Base::print(ostream &output)
{
	cout<<"x="<<x<<endl;
}
int Base::GetX()
{
	return x;
}

class Derived : public Base
{
public : 
	Derived(){y=0;}
	Derived(int xx,int yy):Base(xx){y=yy;}
	void print(ostream &output)
	{
		Base::print( output);
		// 再列印自己的資料
		cout<<"y="<<y<<endl;
	}
	friend ostream & operator << (ostream & , Base &);
private:
	int y;
};

ostream & operator << (ostream & output , Base & anObject)
{
	// 借用了虛函數的機制,可用于該類族的各個類對象。
	anObject . print ( output);
	return output;
} 

//調用方法
//cout<<anObject<<endl;
int main()
{
	//Base b;  //錯誤: cannot instantiate abstract class 
	//cout<<b<<endl;
	Derived d1(2,5);
	Derived d2(3,6);
	cout<<d1<<d2<<endl;
	return 0;
}