为什么我不需要使用命名空间

Why do i need NOT use the namespace?

本文关键字:命名空间 不需要 为什么      更新时间:2023-10-16

所以我有以下功能:

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.