首页 > 解决方案 > 在 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?当然,如果我们在命名空间之外定义这个函数,那么我们就不再使用我们自己的没有限定的类型,而是应该限定它们?或者我们从特定命名空间实现函数这一事实是否解释了这种行为?

标签: c++namespaces

解决方案


正如Igor Tandetnik所说,因为标准是这样说的。对于My_Code::右大括号之间的所有内容,名称查找从 My_Code 开始。

int My_Code::main()定义您的函数 ,main是类型int并且驻留在命名空间My_Code中。这意味着My_Code可以使用其中的功能。因此类型zz2属于 My_Code。


推荐阅读