Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

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

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
{
 public:
  void doIt(int x);
};
class CChild : public CParent
{
 public:
  void doIt(int x,int y,int z);
};

CChild *pChild = ...
pChild->doIt(123); //FAILS compiler, no method found
CParent *pParent = pChild;
pParent->doIt(123); //works fine

How on earth?

EDIT: people are talking about shadowing/hiding. But the two versions of doIt have different numbers of parameters. Surely that can't confuse the compiler, overloads in child class which can't possibly be confused with the parent class version? Can it?

The compiler error I get is: error C2660: 'CChild::doIt' : function does not take 1 argument

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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::<x>; will bring all of base's "<x>" methods into visibility.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...