Best way to call hidden base class method [duplicate]

大憨熊 提交于 2020-06-17 09:04:12

问题


In the following code, "d.Foo()" throws a compiler error claiming that function Foo() does not take 0 arguments. Yet a 0-argument function with that name exists in the base class. The line "d.Base::Foo()" is acceptable.

I have a vague memory of learning that the use of a function name in a derived class hides all functions of that name in a base class, even though arguments may be different. I don't remember why, nor do I remember the best way to avoid that problem. Is my solution best, or is there another way to get at Base::Foo()?

Thanks very much!

RobR

// 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;
}

回答1:


You could define Derived::Foo() as:

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



回答2:


you can use(!) base class member functions via using

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


来源:https://stackoverflow.com/questions/20571818/best-way-to-call-hidden-base-class-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!