在 using 语句中指定 Class 名称有什么作用?
What Does Specifying a Class Name in a using Statement Do?
鉴于以下情况:
namespace Foo{
class Bar{
static const auto PRIVATE = 0;
const int private_ = 1;
void ptivateFunc() { cout << 2; }
public:
static const auto PUBLIC = 3;
const int public_ = 4;
void publicFunc() { cout << 5; }
};
}
语句 using Foo::Bar;
编译...但我不确定它为我提供了访问权限。任何人都可以解释该声明的重点是什么以及它可以让我获得关于 Bar
的内容,而不是简单地做一个 using namespace Bar
?
它允许您在没有 Foo
命名空间的情况下使用 Bar
。
来自 cppreference:
using ns_name::name
; (6)
(...)
6) using-declaration: makes the symbol name
from the namespace ns_name
accessible for unqualified lookup as if declared in the same class scope, block scope, or namespace as where this using-declaration appears.
using namespace ns_name
; (5)
5) using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.
所以基本上你可以在命名空间 Foo
之外(但在 using 声明的范围内)写 Bar
而不是 Foo::Bar
,而来自命名空间 Foo
还需要全名。
如果您使用 using namespace Foo
,您可以通过本地名称访问 Foo
中的所有符号,而无需显式 Foo::
.
鉴于以下情况:
namespace Foo{
class Bar{
static const auto PRIVATE = 0;
const int private_ = 1;
void ptivateFunc() { cout << 2; }
public:
static const auto PUBLIC = 3;
const int public_ = 4;
void publicFunc() { cout << 5; }
};
}
语句 using Foo::Bar;
编译...但我不确定它为我提供了访问权限。任何人都可以解释该声明的重点是什么以及它可以让我获得关于 Bar
的内容,而不是简单地做一个 using namespace Bar
?
它允许您在没有 Foo
命名空间的情况下使用 Bar
。
来自 cppreference:
using
ns_name::name
; (6)
(...)
6) using-declaration: makes the symbolname
from the namespacens_name
accessible for unqualified lookup as if declared in the same class scope, block scope, or namespace as where this using-declaration appears.using namespace
ns_name
; (5)
5) using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from namespace-name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and namespace-name.
所以基本上你可以在命名空间 Foo
之外(但在 using 声明的范围内)写 Bar
而不是 Foo::Bar
,而来自命名空间 Foo
还需要全名。
如果您使用 using namespace Foo
,您可以通过本地名称访问 Foo
中的所有符号,而无需显式 Foo::
.