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




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值