c++ - 在 C++ 命名空间中声明但在其外部定义的函数是否保留了该命名空间中的类型?
问题描述
我参考了 Stroustrup 在 3.3 Namespaces of 'A Tour of C++' 中稍微模糊的例子。他举了以下例子:
namespace My_Code {
class complex { /* ... */ }; // class complex is within My_Code scope
complex sqrt(complex); //takes our locally-defined complex as an argument
int main();
}
// Defining My_Code main function *outside* of the My_Code namespace,
// but this is fine
int My_Code::main() {
complex z {1, 2}; // My_Code::complex, or std::complex?
auto z2 = sqrt(z); // My_Code::sqrt(), or std::sqrt()?
std::cout << '{' << z2.real() << ',' << z2.imag() << "}\n";
// ...
}
int main() {
return My_Code::main();
}
我的问题是:尝试过这个并发现预期的类型来自 My_Code,为什么在这种情况下 z 和 z2 的类型属于 My_Code?当然,如果我们在命名空间之外定义这个函数,那么我们就不再使用我们自己的没有限定的类型,而是应该限定它们?或者我们从特定命名空间实现函数这一事实是否解释了这种行为?
解决方案
正如Igor Tandetnik所说,因为标准是这样说的。对于My_Code::
右大括号之间的所有内容,名称查找从 My_Code 开始。
int My_Code::main()
定义您的函数 ,main
是类型int
并且驻留在命名空间My_Code
中。这意味着My_Code
可以使用其中的功能。因此类型z
和z2
属于 My_Code。
推荐阅读
- python - 无法在 Main() 中调用函数
- css - 尝试添加文本时 CSS 功能“内容”不起作用
- python-requests - 如何在请求(或 urllib3.response)中获取完整的服务器响应消息?
- spring - 文件编码中面临的问题 - 使用文件到字符串转换器的 UTF-8/16
- php - 将“全选”添加到过滤器
- java - SpringBoot:绕过 OncePerRequestFilter 过滤器
- python - Python 子进程打开我的 Pycharm 文件夹和 Jupyter 文件夹而不是目标
- ios - 代码签名错误:SDK“iOS 11.4”中的产品类型“应用程序”需要代码签名
- laravel - Laravel 5 - 将 Auth 模块移入特定模块
- wordpress - 全球 $product 为空 - Timber + Woocommerce