虚函数与友元函数的配合
虚函数具有动态联编性,在类族中有强大功能;友元函数具有跨类访问的功能,但不能继承。
二者若能巧妙结合,会同时发挥各自的功能。
/*
虚函数与友元函数的配合
注意: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;
}