【问题标题】:Access overriden parent virtual method in C++在 C++ 中访问重写的父虚拟方法
【发布时间】:2017-12-12 13:33:08
【问题描述】:

在以下代码中,如何从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?)

【问题讨论】:

  • 您的代码(如您所见)没有调用 f 函数,因此声明的输出与代码不匹配。
  • 已编辑。谢谢。

标签: c++ inheritance virtual


【解决方案1】:
  1. 使用pBase-&gt;Base::g();强制在Base中调用g

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

【讨论】:

  • @Bathsheba 这么简单!谢谢!!
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
相关资源
最近更新 更多