c++ virtual关键字的使用

new的对象是谁,其调用virtual函数时,即调用谁

class father
{
public:
	virtual void v_pp()
	{
		printf("this is virtual father");
	}
	void pp()
	{
		printf("this is father");
	}

};
class child
{
public:
	void v_pp()
	{
		printf("this is virtual child");
	}
	void pp()
	{
		printf("this is child");
	}

	void c_for_p()
	{
		parent::v_pp();
	}
};
int main()
{
	child *c = new child();
	child *p = c;
	//子类访问父类函数
	c->c_for_p();//this is virtual parent;
	
	c->v_pp(); //this is virtual child;
	p->v_pp(); //this is virtual child;
	
	c->pp(); //this is child;
	p->pp(); //this is father;
	
	p = new father();
	c = p;
	c->v_pp(); //this is virtual father;
	p->v_pp(); //this is virtual father;
	
	c->pp(); //this is child;
	p->pp(); //this is father;
}

无virtual关键字时,new的对象是谁,其调用非virtual函数时,即调用谁
此处实际上是c++的隐藏属性
如上代码中的pp即为此功能

子类如何调用父类函数
parent::v_pp()用类名::函数名,即可在子类中访问父类的函数,但要注意的是,父类必须有virtual字段,子类的函数名和形参也必须要和父类的一致,即要打破c++的覆盖属性。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值