nek*_*ute 0 c++ virtual inheritance
在下面的代码,我怎么能访问Base::g()的pBase?(仍然可以pBase->g();像下面那样" "工作
#include <iostream>
using namespace std;
class Base
{
public:
virtual void f(){ cout << "Base::f()" << endl; }
virtual void g(){ cout << "Base::g()" << endl; }
void h(){ cout << "Base::h()" << endl; }
};
class Derived : public Base
{
public:
void f(){ cout << "Derived::f()" << endl; }
virtual void g(){ cout << "Derived::g()" << endl; }
void h(){ cout << "Derived::h()" << endl; }
};
int main()
{
Base *pBase = new Derived;
pBase->f();
pBase->g();
pBase->h();
Derived *pDerived = new Derived;
pDerived->f();
pDerived->g();
pDerived->h();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Derived::f()
Derived::g()
Base::h()
Derived::f()
Derived::g()
Derived::h()
Run Code Online (Sandbox Code Playgroud)
还有,Derived::f()完全一样Derived::g()吗?(即自动定义为virtual?)
用pBase->Base::g();强制的号召g在Base.
是的,Derived::f是virtual.我个人觉得重新强调的virtual是品味不佳.从C++ 11开始,您可以override在重写函数上使用说明符,然后编译器virtual在从基类中删除时发出诊断信息.