c++ 继承类中函数重载的问题

c++ issue with function overloading in an inherited class(c++ 继承类中函数重载的问题)
本文介绍了c++ 继承类中函数重载的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这可能是一个菜鸟问题,抱歉.我最近在尝试处理 C++ 中的一些高级内容、函数重载和继承时遇到了一个奇怪的问题.

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;

有两个类,classAclassB,如下所示;

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

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

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

据我所知 classB 现在应该拥有两个 func(..) 函数,由于不同的参数而重载.

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

它给出错误,因为方法 void func(char[]){}; 位于超类 classA 中,在派生类中不可见,classB.

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

我怎样才能克服这个问题?这不是 C++ 中的重载方式吗?我是 C++ 新手,但在 Java 中,我知道我可以使用这样的东西.

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.

推荐答案

您只需要一个 using:

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

它不会在基类中搜索 func,因为它已经在派生类中找到了.using 语句将另一个重载带入同一作用域,以便它可以参与重载解析.

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.

这篇关于c++ 继承类中函数重载的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)