对象名称与命名空间名称相同:redeclaration

时间:2015-08-18 15:16:23

标签: c++ class scope namespaces objectname

当文件范围中定义的对象与现有命名空间同名时,为什么会出现问题?为什么在功能范围内这是正常的(例如在main中)?

示例:

#include <iostream>

namespace foo {
    class Foo {};
}

namespace bar {
    class Bar {};
}

// foo::Foo foo; // <-- This will give error

int main () {
    bar::Bar bar;  // <-- This is ok

    std::cout << "Program ran successfully" << std::endl;
    return 0;
}

我得到的错误是

ns_main.cpp:11:10: error: ‘foo::Foo foo’ redeclared as different kind of symbol
 foo::Foo foo;
          ^
ns_main.cpp:3:15: error: previous declaration of ‘namespace foo { }’
 namespace foo {

如果在定义了许多不同命名空间的地方包含了大量文件,则很容易实现这种情况。

有人可以解释一下吗?谢谢! 干杯

1 个答案:

答案 0 :(得分:0)

可以在不同的,可能嵌套的范围中声明和使用相同的标识符,但不能在同一个范围内使用。您的问题与命名空间在文件范围定义的事实无关。将它们移动到另一个名称空间outer并不能解决错误:

#include <iostream>

namespace outer {
  namespace foo {
    class Foo {};
  }

  namespace bar {
    class Bar {};
  }
  foo::Foo foo; // <-- This will still give an error
}

int main() {
  outer::bar::Bar bar; // <-- This is still ok
}

bar中的变量bar::Bar bar;属于另一个比名称空间bar更本地的范围。 foo中的变量foo::Foo foo;和命名空间foo的范围完全相同。

由于大多数变量和命名空间不应在全局/文件范围内声明,因此拥有多个命名空间根本不是问题。