C++继承和函数重写
在 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 抛出
error: no matching function for call to `Y::spray(A&)'
note: candidates are: void Y::spray(B&)
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.
#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&)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用于描述这一点的术语是“隐藏”,而不是“覆盖”。默认情况下,派生类的成员将使任何具有相同名称的基类成员不可访问,无论它们是否具有相同的签名。如果要访问基类成员,可以使用
using
声明将它们拉入派生类。在本例中,将以下内容添加到Y 类
: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 toclass Y
:这就是所谓的“隐藏”:
Y::spray
隐藏X::spray
。添加 using 指令:
That's so called 'hiding':
Y::spray
hidesX::spray
.Add using directive:
类是作用域,类作用域嵌套在其父级中。对于其他嵌套作用域(命名空间、块),您具有完全相同的行为。
发生的情况是,当名称查找搜索名称的定义时,它会在当前名称空间中查找,然后在 englobing 名称空间中查找,依此类推,直到找到一个定义;然后搜索停止(这没有考虑参数相关名称查找引入的复杂性——规则的一部分允许使用在其参数之一的命名空间中定义的函数)。
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).