为什么我不需要使用命名空间
Why do i need NOT use the namespace?
所以我有以下功能:
GraSys::CRectangle GraSys::CPlane::boundingBox(std::string type, std::string color)
{
CRectangle myObject = CRectangle(color);
return myObject;
}
由于 boundingBox 是命名空间 GraSys 的一部分,我必须使用它才能声明这个函数,为什么我不需要在函数内这样做?,为什么我可以只使用? 为什么它让我编译没有问题?
CRectangle myObject = CRectangle(color);
而不是:
GraSys::CRectangle myObject = GraSys::CRectangle(color);
希望我的问题不会令人困惑。
您正在实现一个在 GrasSys 命名空间中声明的函数。在该函数中时,使用声明名称空间。
为清楚起见,请考虑:
namespace GraSys {
class CRectangle { ... };
class CPlane {
... boundingBox(...); ...
}
void example(...) { ... };
}
当你实现边界框时,你将在函数声明期间声明的命名空间中,即 GraSys。CRectangle是在GraSys中声明的,因此您可以直接使用它。同样,请注意,您也可以直接调用函数,因此在上面的代码中,您可以直接在 boundingBox 实现中调用示例。
这
称为非限定名称查找。您可以在C++标准部分中阅读完整的查找规则3.4.1
或在此处以更易于阅读的形式阅读。
以下是标准的一个例子,可能比冗长的解释更好:
namespace A {
namespace N {
void f();
}
}
void A::N::f() {
i = 5;
// The following scopes are searched for a declaration of i:
// 1) outermost block scope of A::N::f, before the use of i
// 2) scope of namespace N
// 3) scope of namespace A
// 4) global scope, before the definition of A::N::f
}
using namespace
就像将命名空间添加到全局命名空间(即 :: 命名空间)一样。 如果这样做,从现在开始,编译器将在所有使用的命名空间中查找每个符号。
只有在存在歧义的情况下(表示在 2 个使用的名称空间中声明的具有相同名称的符号,您将不得不为其使用命名空间。
namespace A{
void f();
void g();
}
namespace B{
void g();
}
using namespace A;
using namespace B;
A::f(); //always work
f(); //work since it is the only symbol named f
A::g();//always work
B::g();//always work
g();// error since g is ambiguous.
相关文章:
- C++:对不存在的命名空间使用命名空间指令
- 是否可以将函数导入命名空间,但不能导出它?
- 嵌套命名空间的"using"指令,但需要命名内部命名空间
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 命名空间 std:: 不包含可选
- 有没有办法不使用命名空间中的项?
- 转发声明在命名空间中不起作用的替代方法
- 为什么在这种特殊情况下不需要将 std::hash() 的专用化注入到 std 命名空间中?
- 命名空间:不能在没有对象的情况下调用成员函数
- 范围运算符需要查找 std 命名空间而不是提升
- 当类方法不进行时,为什么从标头文件中的独立方法需要为命名空间资格
- 为什么在使用命名空间时需要 c++ 命名空间说明符
- 为什么我不需要使用命名空间
- 为什么某些 Boost 函数不需要以命名空间为前缀
- c++命名空间新手需要帮助
- 为什么regex_search不需要命名空间
- 为什么遗留C标识符不需要命名空间std
- C++ getline() 不需要命名空间声明
- 使用 isalpha 函数时不需要 std 命名空间
- 我想从这段代码中删除使用命名空间std,但我不确定什么都需要用std::作为前缀