C++ Base Class Function Overloading in a Subclass [duplicate]

萝らか妹 提交于 2021-02-05 08:34:48

问题


Given the following...

#include <iostream>
using namespace std;

class BaseClass {
public:
    void Func(float f) {
        cout << "BaseClass:Func() called!";
    }
};

class SubClass : public BaseClass {
};

int main() {
    SubClass sub;
    sub.Func(1.1f);
    return 0;
}

This runs pretty much as one would expect, resulting in the following output...

BaseClass:Func() called!

However, if I add the following function to SubClass...

class SubClass : public BaseClass {
public:
    void Func(int i) {                        // accepts an int, not a float!
        cout << "SubClass::Func() called!";
    }
};

Like any other overload, I would expect the SubClass function to be called if I supply an int as my argument, and BaseClass's if I supply a float. However, if I run the program as-is (ie. with the float), this is not the case...

SubClass::Func() called!

Instead of what I was expecting, the float I provided is cast to an integer, and the SubClass function is called. It seems SubClass's function effectively shadows BaseClass's function, even though its signature differs.

Can someone shed some light on this? Is there a way to call the BaseClass function via a SubClass instance without having to cast it?

Thanks!


回答1:


As you said, the BaseClass's function is hidden by the SubClass's. The name Func will be found at the SubClass's scope, then name lookup stops, Func in BaseClass won't be considered at all, even it's more appropriate. They're not "overloads" at all.

See Unqualified name lookup.

You can use using to introduce them into the same scope to make overloading works.

class SubClass : public BaseClass {
public:
    using BaseClass::Func;
    ~~~~~~~~~~~~~~~~~~~~~
    void Func(int i) {                        // accepts an int, not a float!
        cout << "SubClass::Func() called!";
    }
};



回答2:


The subclass' Func method will hide the base class' Func method in the member name lookup, and will thus be called with any numeric argument, casted to an integer.

If you want to use both methods in the subclass, pull the base class' Func method by using using BaseClass::Func;. This will treat the base Func as being a member of the subclass, no longer being hidden by the subclass' name lookup.



来源:https://stackoverflow.com/questions/35870081/c-base-class-function-overloading-in-a-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!