【问题标题】:Best way to call hidden base class method [duplicate]调用隐藏基类方法的最佳方法[重复]
【发布时间】:2014-01-01 12:51:20
【问题描述】:

在以下代码中,“d.Foo()”会引发编译器错误,声称函数 Foo() 不接受 0 个参数。然而,基类中存在一个具有该名称的 0 参数函数。 “d.Base::Foo()”行是可以接受的。

我有一个模糊的记忆,知道在派生类中使用函数名会将所有具有该名称的函数隐藏在基类中,即使参数可能不同。我不记得为什么,也不记得避免这个问题的最佳方法。我的解决方案是最好的,还是有其他方法可以访问 Base::Foo()?

非常感谢!

罗伯R

// Override.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
class Base
{
public :
    void Foo()
    {
    }
};

class Derived : public Base
{
public: 
    void Foo(int x)
    {
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Derived d;
    d.Foo();
    d.Base::Foo();

    return 0;
}

【问题讨论】:

  • 非常感谢。我的问题确实是那个问题的重复,对此的回答非常好。

标签: c++ overriding hidden


【解决方案1】:

您可以通过using 使用(!)基类成员函数

class Derived : public Base {
public:
    using Base::Foo;
};

【讨论】:

    【解决方案2】:

    您可以将Derived::Foo() 定义为:

    class Derived : public Base {
    public:
        void Foo() { Base::Foo(); }
    };
    

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 2013-03-11
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多