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
84 views
in Technique[技术] by (71.8m points)

c++ issue with function overloading in an inherited class

This is possibly a noob question, sorry about that. I faced with a weird issue recently when trying to mess around with some high level stuff in c++, function overloading and inheritance.

I'll show a simple example, just to demonstrate the problem;

There are two classes, classA and classB, as below;

class classA{
    public:
        void func(char[]){};    
};

class classB:public classA{ 
    public:
        void func(int){};
};

According to what i know classB should now posses two func(..) functions, overloaded due to different arguments.

But when trying this in the main method;

int main(){
    int a;
    char b[20];
    classB objB;
    objB.func(a);    //this one is fine
    objB.func(b);    //here's the problem!
    return 0;
}

It gives errors as the method void func(char[]){}; which is in the super class, classA, is not visible int the derived class, classB.

How can I overcome this? isn't this how overloading works in c++? I'm new to c++ but in Java, i know I can make use of something like this.

Though I've already found this thread which asks about a similar issues, I think the two cases are different.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

All you need is a using:

class classB:public classA{ 
    public:
        using classA::func;
        void func(int){};
};

It doesn't search the base class for func because it already found one in the derived class. The using statement brings the other overload into the same scope so that it can participate in overload resolution.


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

...