C++11 virtual函数学习笔记

#include<iostream>
#include<string>
using namespace std;
class Base
{
public:
	Base(){}
	~Base(){}
public:
	virtual void f1(int x){ cout << "baseclass: f1() " << x << endl; }
	virtual void f2()final{ cout << "baseclass: f2()  " << endl; }
	void f3(int x){ cout << "baseclass : f3() " <<x<< endl; }
	virtual void f4(){ cout << "baseclass:f4()" << endl; }
	//string isbn()const;
	//virtual double net_price(size_t n)const final;
};
class Derive:public Base
{
public:
	Derive(){}
	~Derive(){}
public:
	//与基类的virtual函数同名不同参数的是重载函数,不能加上override,可以加virtual
	void f1(double x){ cout << "double derive class :f1()" << x << endl; }
	//与基类的virtual函数同名同参数的是覆盖函数,可以加virtual,override
	void f1(int x)override{ cout << "int  derived class :f1()" << x << endl; }
	//基类的f2()加了final,于是去掉注释出错
	//void f2()override{ cout << "override derived class: f2() " << endl; }
	//但是奇怪的来了,与基类的非virtual函数同名同参数的是竟然也是覆盖函数!
	//如果去掉注释则会输出“"derive class: f3()”
	//我认为应该产生编译错误,但是却没有
	//void f3(int x){ cout << "derive class: f3() " <<x << endl; }
 
	//我们看f4()没有任何问题,因为baseclass中声明是virtual,在派生类中会自动把f4()变为virtual
	void f4(){ cout << "derive class :f4() " << endl; }
};
int main()
{
	Base*  pBase = new Base();
	pBase->f1(1);
	pBase->f2();
	pBase->f3(3);
	pBase->f4();
	cout << endl;
	Derive* pDerive = new Derive();
	pDerive->f1(2.0);
	pDerive->f1(2);
	//pDerive->f2();
	pDerive->f3(3);
	pDerive->f4();
	cout << endl;
	return 0;
}
问题我已经自己解决,原来与virtual函数无关,只是名字冲突与继承的问题。派生类的成员会隐藏同名的基类成员。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值