C++ : multiple namespaces inside a function

标签 c++ namespaces

<分区>

我正在尝试下面的代码,在一个函数中使用多个命名空间(更改命名空间)。我不确定哪里出了问题,我什至不确定我是否可以像下面这样使用,但在我短暂的浏览中没有找到任何矛盾的证据,请告诉我哪里出了问题:

#include <iostream>
using namespace std;

namespace standard_one
{
        int i = 10;
}

namespace standard_two
{
        int i = 40;
}


main()
{
        using namespace standard_one;
        cout << "value of i is " << i << endl;

        {
                using namespace standard_two;
                cout << "value of i after namespace change is " << i << endl; // Compilation error here, compiler is complaining that "i" is undeclared
        }
}

最佳答案

这不是未声明,而是模棱两可。两个 using 指令都适用于内部范围,因此两个 i 都被引入了范围。如果不完全限定名称,编译器就无法知道您指的是哪一个。

您可以使用完全限定名称并说出 standard_one::istandard_two::i 来解决歧义。

题外话:

   int main() {
// ^^^ !!!

关于C++ : multiple namespaces inside a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17342741/

相关文章:

c++ - C++ 中宽字符的问题

c++ - 缺少关于 "int main(int argc, char* argv[])"的知识

c++ - Pragma omp 并行部分

C++:将 vector reshape 为 3D 数组

c++ - 范围基数并插入 vector C++11

单独文件中的 C# 命名空间/类在查看时导致错误

.net - 如何在 .NET/C#/VS2008 中的项目之间共享命名空间。接收错误 : "are you missing an assembly reference?"

c++ - 命名空间中的模板函数导致错误

c# - 引用程序集后无法使用命名空间

c++ - 只有静态方法的类比命名空间更可取吗?