C++ inheritance, base methods hidden

前端 未结 2 2044
一生所求
一生所求 2020-12-06 20:05

I have a simple C++ base class, derived class example.

// Base.hpp 
#pragma once

class Base
{
public:
    virtual float getData();
    virtual void setData(         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 20:50

    This is an artifact of C++ name lookup. The basic algorithm is the compiler will start at the type of the current value and proceed up the hierarchy until it finds a member on the type which has the target name. It will then do overload resolution on only the members of that type with the given name. It does not consider members of the same name on parent types.

    The way to work around this is to redefine the functions on Derived and just forward them up to Base

    class Derived {
      ...
      void setData(float a, float b);
    }
    
    void Derived::setData(float a, float b) {
      Base::setData(a,b);
    }
    

    Additionally you can bring the base members into scope using the using declaration

    class Derived {
      using Base::setData;
      ...
    }
    

    Documentation on this use of using

    • http://publib.boulder.ibm.com/infocenter/comphelp/v101v121/index.jsp?topic=/com.ibm.xlcpp101.aix.doc/language_ref/using_declaration_class_members.html

提交回复
热议问题