派生类中具有相同名称但不同签名的函数

Function with same name but different signature in derived class(派生类中具有相同名称但不同签名的函数)

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

问题描述

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

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.

通常认为在派生类中具有与基类中的函数同名的函数是不好的做法,这些函数并不打算覆盖基类函数,因为您所看到的通常不是可取的行为.通常最好给不同的函数起不同的名字.

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.

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

本文标题为:派生类中具有相同名称但不同签名的函数

基础教程推荐