[英]Access overriden parent virtual method in C++
In the following code, how can I access Base::g()
from pBase
? 在以下代码中,如何从
pBase
访问Base::g()
? (and still get " pBase->g();
" to work as it does below) (并且仍然获得“
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;
}
Output is: 输出为:
Derived::f()
Derived::g()
Base::h()
Derived::f()
Derived::g()
Derived::h()
Also, is Derived::f()
exactly the same as Derived::g()
? 另外,
Derived::f()
与Derived::g()
完全相同吗? (ie. automatically defined as virtual
?) (即自动定义为
virtual
?)
Use pBase->Base::g();
使用
pBase->Base::g();
to force the call of g
in Base
. 强制
g
在Base
调用。
Yes, Derived::f
is virtual
. 是的,
Derived::f
是virtual
。 I personally find the re-emphasising of virtual
to be in poor taste. 我个人发现对
virtual
的重新强调会让人觉得不好。 Since C++11, you can use the override
specifier on overridden functions, and then a compiler issues a diagnostic if virtual
is dropped from the base class. 从C ++ 11开始,可以对重写的函数使用
override
说明符,然后,如果从基类中删除了virtual
,则编译器将发出诊断信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.