子类中的 C++ 基类函数重载 [英] C++ Base Class Function Overloading in a Subclass

查看:66
本文介绍了子类中的 C++ 基类函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下...

#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() 被调用!

BaseClass:Func() called!

但是,如果我将以下函数添加到 SubClass...

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

像任何其他重载一样,如果我提供一个 int 作为我的参数,我希望 SubClass 函数被调用,如果我提供一个浮点数,我希望调用 BaseClass 函数.但是,如果我按原样运行程序(即使用浮点数),则情况并非如此...

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() 被调用!

SubClass::Func() called!

不是我所期望的,我提供的浮点数被转换为一个整数,并调用了 SubClass 函数.似乎 SubClass 的函数有效地掩盖了 BaseClass 的函数,即使其签名不同.

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.

有人可以对此有所了解吗?有没有办法通过 SubClass 实例调用 BaseClass 函数而不必强制转换?

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?

谢谢!

推荐答案

正如你所说,BaseClass 的功能被 SubClass 隐藏了.名称 Func 将在 SubClass 的范围内找到,然后名称查找停止,BaseClass 中的 Func 获胜根本不考虑,甚至更合适.它们根本不是超载".

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.

请参阅非限定名称查找.

你可以使用 using 将它们引入到同一个作用域中,使重载起作用.

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

这篇关于子类中的 C++ 基类函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆