C++ method only visible when object cast to base class?

后端 未结 7 2412
栀梦
栀梦 2020-11-29 10:27

It must be something specific in my code, which I can\'t post. But maybe someone can suggest possible causes.

Basically I have:

class CParent
{
 publ         


        
7条回答
  •  既然无缘
    2020-11-29 11:01

    You have shadowed a method. For example:

    struct base
    {
        void method(int);
        void method(float);
    };
    
    struct derived : base
    {
        void method(int);
        // base::method(int) is not visible.
        // base::method(float) is not visible.
    };
    

    You can fix this with a using directive:

    class derived : public base
    {
        using base::method; // bring all of them in.
    
        void method(int);
        // base::method(int) is not visible.
        // base::method(float) is visible.
    };
    

    Since you seem insistent about the number of parameters, I'll address that. That doesn't change anything. Observe:

    struct base
    {
        void method(int){}
    };
    
    struct derived : base
    {
        void method(int,int){}
        // method(int) is not visible.
    };
    
    struct derived_fixed : base
    {
        using base::method;
        void method(int,int){}
    };
    
    int main(void)
    {
        {
            derived d;
    
            d.method(1, 2); // will compile
            d.method(3); // will NOT compile
        }
        {
            derived_fixed d;
    
            d.method(1, 2); // will compile
            d.method(3); // will compile
        }
    }
    

    It will still be shadowed regardless of parameters or return types; it's simply the name that shadows. using base::; will bring all of base's "" methods into visibility.

提交回复
热议问题