c++ - 在 C++ 中访问重写的父虚方法

标签 c++ inheritance virtual

在下面的代码中,如何从 pBase 访问 Base::g()? (并且仍然让“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;
}

输出是:

Derived::f()
Derived::g()
Base::h()
Derived::f()
Derived::g()
Derived::h()

此外,Derived::f() 是否与 Derived::g() 完全相同? (即自动定义为 virtual?)

最佳答案

  1. 使用pBase->Base::g();强制调用Base中的g

  2. 是的,Derived::f虚拟的。我个人认为重新强调 virtual 的品味很差。从 C++11 开始,您可以在重写的函数上使用 override 说明符,然后如果 virtual 从基类中删除,编译器会发出诊断。

关于c++ - 在 C++ 中访问重写的父虚方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47773930/

相关文章:

c++ - Clion mongodb 依赖设置

android - Genymotion 无法创建帧缓冲区图像,没有得到任何可行的解决方案

C++虚拟类基础题

c++ - vtable 在虚拟继承的情况下

c++ - 为 llvm::ConstantInt 设置值

c++ - VOID 是指 'nothing' 还是 'anything'

C++ - 最佳实践#define 只写一次的值?

c# - WCF 服务对象序列化

c# - 使用派生类型和同名 C# 覆盖属性

c++ - 将基类转换为其派生类之一?