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

标签 c++ function inheritance lookup c++-faq

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

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 编译器收到以下错误:

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 重命名它,一切正常美好的。

这有什么问题?

最佳答案

这是因为如果在您的一个基地中找到名称,名称查找就会停止。它不会超越其他基地。 B 中的函数隐藏 A 中的函数。您必须在 B 的范围内重新声明 A 的函数,以便从 B 和 C 中都可以看到这两个函数:

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

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

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

编辑:标准给出的真实描述是(从 10.2/2 开始):

The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub- object B hides a member name f in a sub-object A if A is a base class sub-object of B. Any declarations that are so hidden are eliminated from consideration. Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declara- tion designated by the using-declaration.96) If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed. Otherwise that set is the result of the lookup.

在另一个地方(就在它上面)有以下说法:

For an id-expression [something like "foo"], name lookup begins in the class scope of this; for a qualified-id [something like "A::foo", A is a nested-name-specifier], name lookup begins in the scope of the nested-name-specifier. Name lookup takes place before access control (3.4, clause 11).

([...] 由我提出)。请注意,这意味着即使您在 B 中的 foo 是私有(private)的,仍然无法找到 A 中的 foo(因为稍后会发生访问控制)。

关于c++ - 派生类中具有相同名称但不同签名的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/411103/

相关文章:

c++ - 指向模板函数的指针

c++ - 使用虚函数与​​ dynamic_cast

javascript - 在下划线模板中使用函数

c++ - 没有构造函数实例 "Class:Class"匹配参数列表

C++ 继承/VTable 问题

c++ 'if' 和 'else' 语句似乎都被调用

c++ - clang/g++ 与友元函数的区别

python - 为什么对全局变量的错误分配会提早引发异常?

Javascript:链接对象/列表函数返回未定义

java - 具有自己变量的子类的复制构造函数