为什么不允许成员函数和非成员函数之间的函数重载?
Why is function overloading between member functions and non-member functions not allowed?
在下面的代码中:
void overload() {}
struct Struct {
void overload(int arg1) {}
void member() {
overload(1); //compiles
overload(); //error: too few arguments [...] did you mean '::overloaded'?
}
};
如果我将 struct
更改为 namespace
,我会得到类似的结果,只是错误消息略有不同。
为什么存在同名成员函数时,编译器不能select通过运算符重载非成员函数?
作为参考,以下所有情况都按预期工作:
- 从非会员中选择两个非会员(显然)
- 从一个成员中选择两个成员
- 从一个成员中选择两个非成员
因为 name lookup 无法找到全局范围内的名称 overload
,它被 Struct::overload
隐藏了。它没有机会参与稍后发生的重载决议。
(强调我的)
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
你主要是在问为什么,而不是说"because the language says so",让我们举一个例子,你的建议导致一切失败。
假设我的 github 存储库中有一个方便的 class:
struct HandyClass {
void display(short c) {
std::cout << c;
}
void doStuff() {
display(3);
}
};
然后其他一些开发人员在不同的 github 复制中制作了一组方便的显示功能:
void display(double v) {
showWindowsPopup("Your score was %f", v);
}
void display(int v) {
showWindowsPopup("Your score was %d", v);
}
您下载了两个 repro,突然,HandyClass 不再正常工作了:
#include "displays.h"
#include "handyclass.h"
int main() {
HandyClass a;
a.doStuff(); //Why does this show a windows popup!?!?
}
因为您首先包括显示 headers,然后 display(3)
匹配到 ::display(int)
而不是 ::HandyClass::display(short)
,因为 3
是一个 int
.很多悲伤都发生了。
但是使用官方的 C++ 查找规则,这不会发生。由于我的 class 有 display
个函数,它会忽略 class 之外的函数以防止出错,所以 HandyClass
总是为每个人做同样的事情。
在下面的代码中:
void overload() {}
struct Struct {
void overload(int arg1) {}
void member() {
overload(1); //compiles
overload(); //error: too few arguments [...] did you mean '::overloaded'?
}
};
如果我将 struct
更改为 namespace
,我会得到类似的结果,只是错误消息略有不同。
为什么存在同名成员函数时,编译器不能select通过运算符重载非成员函数?
作为参考,以下所有情况都按预期工作:
- 从非会员中选择两个非会员(显然)
- 从一个成员中选择两个成员
- 从一个成员中选择两个非成员
因为 name lookup 无法找到全局范围内的名称 overload
,它被 Struct::overload
隐藏了。它没有机会参与稍后发生的重载决议。
(强调我的)
name lookup examines the scopes as described below, until it finds at least one declaration of any kind, at which time the lookup stops and no further scopes are examined.
你主要是在问为什么,而不是说"because the language says so",让我们举一个例子,你的建议导致一切失败。
假设我的 github 存储库中有一个方便的 class:
struct HandyClass {
void display(short c) {
std::cout << c;
}
void doStuff() {
display(3);
}
};
然后其他一些开发人员在不同的 github 复制中制作了一组方便的显示功能:
void display(double v) {
showWindowsPopup("Your score was %f", v);
}
void display(int v) {
showWindowsPopup("Your score was %d", v);
}
您下载了两个 repro,突然,HandyClass 不再正常工作了:
#include "displays.h"
#include "handyclass.h"
int main() {
HandyClass a;
a.doStuff(); //Why does this show a windows popup!?!?
}
因为您首先包括显示 headers,然后 display(3)
匹配到 ::display(int)
而不是 ::HandyClass::display(short)
,因为 3
是一个 int
.很多悲伤都发生了。
但是使用官方的 C++ 查找规则,这不会发生。由于我的 class 有 display
个函数,它会忽略 class 之外的函数以防止出错,所以 HandyClass
总是为每个人做同样的事情。