C++虚函数的新用法

时间:2023-03-09 05:57:39
C++虚函数的新用法

1.今天在segmentfault上看到了一个C++虚函数的新用法,先上代码

#include <iostream>
using namespace std; class B {
public:
virtual void f() { cout << "virtual function" << endl; }
}; class D : public B {
private:
void f() { cout << "private function" << endl; }
}; int main()
{
D d;
B* pb = &d;
pb->f();
}

输出结果:private function

  • 导致这一结果的原来是: 虚方法的权限只由其声明确定,并不受后续 override 函数权限的影响

文章来源:http://segmentfault.com/blog/pezy/1190000002513126