继承(4)

版权声明:私藏源代码是违反人性的罪恶行为!博客转载无需告知,学无止境。 https://blog.csdn.net/qq_41822235/article/details/83060277

继承(3)

情景:基类虚函数属性是public,派生类虚函数属性是private,使用基类指针指向子类对象,该指针能调用基类私有的函数。

#include<iostream>
using namespace std;
class Base
{
public:
	virtual void show()
	{
		cout << "Base::show()" << endl;
	}
};

class Derive : public Base
{
private:
	virtual void show()
	{
		cout << "Derive::show()" << endl;
	}
};

int main()
{
	Base* p1 = new Derive();
	p1->show();
    return 0;
}

分析: 基类指针在编译时就确定在其运行时会到子类的虚表中调用该函数,private修饰失效了。

图1 VS2017下运行结果

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/83060277