派生类中同名但签名不同的函数 [英] Function with same name but different signature in derived class

查看:31
本文介绍了派生类中同名但签名不同的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个同名的函数,但在基类和派生类中具有不同的签名.当我尝试在从派生类继承的另一个类中使用基类的函数时,我收到一个错误.看下面的代码:

I have a function with the same name, but with different signature in a base and derived classes. When I am trying to use the base class's function in another class that inherits from the derived, I receive an error. See the following code:

class A
{
    public:
    void foo(string s){};
};

class B : public A
{
    public:
    int foo(int i){};
};

class C : public B
{
    public:
    void bar()
    {
        string s;
        foo(s);
    }
};

我从 gcc 编译器收到以下错误:

I receive the following error from the gcc compiler:

In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int)

如果我从 B 类中删除 int foo(int i){};,或者如果我从 foo1 重命名它,一切正常美好的.

If I remove int foo(int i){}; from class B, or if I rename it from foo1, everything works fine.

这有什么问题?

推荐答案

派生类中的函数不覆盖基类中的函数但具有相同名称的函数将隐藏其他相同的函数基类中的名称.

Functions in derived classes which don't override functions in base classes but which have the same name will hide other functions of the same name in the base class.

在派生类中使用与bass类中的函数同名的函数通常被认为是不好的做法,这些函数不打算覆盖基类函数,因为您所看到的通常不是理想的行为.通常最好为不同的函数赋予不同的名称.

It is generally considered bad practice to have have functions in derived classes which have the same name as functions in the bass class which aren't intended to override the base class functions as what you are seeing is not usually desirable behaviour. It is usually preferable to give different functions different names.

如果您需要调用基本函数,则需要使用A::foo(s) 来限定调用范围.请注意,这也会同时禁用 A::foo(string) 的任何虚函数机制.

If you need to call the base function you will need to scope the call by using A::foo(s). Note that this would also disable any virtual function mechanism for A::foo(string) at the same time.

这篇关于派生类中同名但签名不同的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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