重载的子 class 函数无法调用相似名称的父函数
Overloaded child class function cannot call parent of similar name
我假设这是“它不是如何工作”的问题之一,但我不明白为什么。为什么我需要用 A::
限定 B
对 A
的 Start
的调用。如果我将 B::Start()
更改为 B::DoSomethingElse()
,我可以在没有 A::
的情况下调用更少的参数 Start()
。那么发生了什么?
#include <iostream>
#include <string>
class A {
public:
void Start(){
}
};
class B : public A {
public:
void Start(int x){
Start(); // cannot call this
A::Start(); // can call this
}
};
B
的class定义中使用的非限定名称Start
class B : public A {
public:
void Start(int x){
Start(); // cannot call this
A::Start(); // can call this
}
};
首先在classB
的范围内搜索,找到这样的名称是因为class声明了函数Start
。即派生 class B
中声明的名称 Start
隐藏了基 class A
中声明的相同名称。要访问在基础 class A
中声明的名称 Start
,您必须使用限定名称。
来自 C++ 标准(草稿,强调我的)[basic.lookup.unqual]/1
:
In all the cases listed in 6.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed.
因此 Start
名称已在 class B
内找到,因此查找停止。重载解析仅在名称查找完成后发生 [basic.lookup]/1
:
...Overload resolution (16.3)
takes place after name lookup has succeeded....
所以即使 class A
和 B
有不同的参数,这在这里不起作用,因为名称查找已经完成。
当您执行 A::Start()
时,您正在使用限定名称查找,您实际上是在其中指定函数出现的 class,因此名称解析将找到该版本。
我假设这是“它不是如何工作”的问题之一,但我不明白为什么。为什么我需要用 A::
限定 B
对 A
的 Start
的调用。如果我将 B::Start()
更改为 B::DoSomethingElse()
,我可以在没有 A::
的情况下调用更少的参数 Start()
。那么发生了什么?
#include <iostream>
#include <string>
class A {
public:
void Start(){
}
};
class B : public A {
public:
void Start(int x){
Start(); // cannot call this
A::Start(); // can call this
}
};
B
Start
class B : public A {
public:
void Start(int x){
Start(); // cannot call this
A::Start(); // can call this
}
};
首先在classB
的范围内搜索,找到这样的名称是因为class声明了函数Start
。即派生 class B
中声明的名称 Start
隐藏了基 class A
中声明的相同名称。要访问在基础 class A
中声明的名称 Start
,您必须使用限定名称。
来自 C++ 标准(草稿,强调我的)[basic.lookup.unqual]/1
:
In all the cases listed in 6.4.1, the scopes are searched for a declaration in the order listed in each of the respective categories; name lookup ends as soon as a declaration is found for the name. If no declaration is found, the program is ill-formed.
因此 Start
名称已在 class B
内找到,因此查找停止。重载解析仅在名称查找完成后发生 [basic.lookup]/1
:
...Overload resolution (16.3) takes place after name lookup has succeeded....
所以即使 class A
和 B
有不同的参数,这在这里不起作用,因为名称查找已经完成。
当您执行 A::Start()
时,您正在使用限定名称查找,您实际上是在其中指定函数出现的 class,因此名称解析将找到该版本。