C++ 继承和函数覆盖
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2161462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ inheritance and function overriding
提问by legends2k
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? 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.
在 C++ 中,基类的成员函数是否会被其同名的派生类函数覆盖,即使其原型(参数的数量、类型和常量)不同?我想这是一个愚蠢的问题,因为许多网站都说函数原型应该是相同的;但是为什么下面的代码不能编译?我相信这是一个非常简单的继承案例。
#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
海湾合作委员会抛出
error: no matching function for call to `Y::spray(A&)'
note: candidates are: void Y::spray(B&)
回答by Mike Seymour
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. In this case, add the following to class Y
:
用于描述这一点的术语是“隐藏”,而不是“覆盖”。默认情况下,派生类的成员将使具有相同名称的基类的任何成员无法访问,无论它们是否具有相同的签名。如果要访问基类成员,可以使用using
声明将它们拉入派生类。在这种情况下,将以下内容添加到class Y
:
using X::spray;
回答by Alexander Poluektov
That's so called 'hiding': Y::spray
hides X::spray
.
Add using directive:
这就是所谓的“隐藏”:Y::spray
隐藏X::spray
。添加 using 指令:
class Y : public X
{
public:
using X::spray;
// ...
};
回答by AProgrammer
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).
发生的情况是,当名称查找搜索名称的定义时,它先在当前名称空间中查找,然后在全局名称空间中查找,依此类推,直到找到一个定义;搜索然后停止(这没有考虑参数相关名称查找引入的复杂性——规则的一部分,允许使用在其参数之一的命名空间中定义的函数)。