简体   繁体   English

C ++继承和功能覆盖

[英]C++ inheritance and function overriding

In C++, will a member function of a base class be overridden by its derived class function of the same name, even if its prototype (parameters' count, type and constness) is different ? 在C ++中, 即使原型(参数的数量,类型和常量)不同,基类的成员函数也会被同名的派生类函数覆盖吗? I guess this a silly question, since many websites says that the function prototype should be the same for that to happen; 我猜这是一个愚蠢的问题,因为许多网站都说功能原型应该是相同的。 but why doesn't the below code compile? 但是为什么下面的代码不能编译? It's a very simple case of inheritance, I believe. 我认为,这是一个非常简单的继承案例。

#include <iostream>
using std::cout;
using std::endl;

class A {};
class B {};

class X
{
public:
    void spray(A&)
    {
        cout << "Class A" << endl;
    }
};

class Y : public X
{
public:
    void spray(B&)
    {
        cout << "Class B" << endl;
    }
};

int main()
{
    A a;
    B b;
    Y y;

    y.spray(a);
    y.spray(b);

    return 0;
}

GCC throws GCC抛出

error: no matching function for call to `Y::spray(A&)'
note: candidates are: void Y::spray(B&)

The term used to describe this is "hiding", rather than "overriding". 用于描述此内容的术语是“隐藏”,而不是“覆盖”。 A member of a derived class will, by default, make any members of base classes with the same name inaccessible, whether or not they have the same signature. 默认情况下,派生类的成员将使具有相同名称的基类的任何成员均不可访问,无论它们是否具有相同的签名。 If you want to access the base class members, you can pull them into the derived class with a using declaration. 如果要访问基类成员,则可以using声明将它们拉入派生类。 In this case, add the following to class Y : 在这种情况下,将以下内容添加到class Y

using X::spray;

That's so called 'hiding': Y::spray hides X::spray . 所谓的“隐藏”: Y::spray隐藏X::spray Add using directive: 使用指令添加:

class Y : public X
{
public:
   using X::spray;
   // ...
};

Classes are scopes and a class scope is nested in its parent. 类是范围,类范围嵌套在其父级中。 You have exactly the same behavior with other nested scopes (namespaces, blocks). 您与其他嵌套作用域(命名空间,块)具有完全相同的行为。

What happen is that when the name lookup searches for the definition of a name, it looks in the current namespace, then in the englobing namespace and so on until it find one definition; 发生的事情是,当名称查找搜索名称的定义时,它将在当前名称空间中查找,然后在包含名称空间的名称中查找,依此类推,直到找到一个定义; the search then stop (that's without taking into account the complications introduced by argument dependent name lookup -- the part of the rules which allows to use a function defined in the namespace of one of its argument). 然后搜索就停止了(这没有考虑参数依赖名称查找所带来的复杂性-规则的一部分,该规则允许使用在其参数之一的名称空间中定义的函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM