4

我只是好奇为什么它是用 using 指令这样设计的。对于 1) struct 被视为命名空间,对于 2) 它不是:

struct foo
{
  using type0 = int;
};

namespace bar
{
  using type1 = int;
}

using bar::type1; 
using type0 = foo::type0; // 1)
using foo::type0;         // 2)

clang version 3.3 (branches/release_33 186829)
clang -std=c++11 test.cpp
test.cpp:13:12: error: using declaration can not refer to class member
using foo::type0;

~~~~~^

gcc version 4.8.1
c++ -std=c++11 test.cpp
test.cpp:13:12: error: ‘foo’ is not a namespace
using foo::type0;
4

1 回答 1

11

类不是命名空间;他们有一个严格的范围。类成员的名称(当在类外部访问时)必须始终以类名作为前缀。

using不允许改变它。

#1 起作用的原因是因为您为类中声明的类型创建了类型别名。就是using name = typename;这样。在这种情况下,它与typedef.

#2 不创建别名;该语法期望在命名空间中被赋予一个名称以带入当前命名空间。

于 2013-08-01T19:12:06.267 回答