9

如果 C++ 中的名称不是完全限定的,例如std::cout,它可能会导致意外错误,例如在https://en.cppreference.com/w/cpp/language/qualified_lookup中提到的。但是正如我所注意到的,为命名空间使用完全限定名称::stdeq::std::cout是非常罕见的。

是否有任何理由::std不使用命名空间的完全限定名称?

为自己创建的命名空间使用完全限定名称又如何呢?这是个好主意吗?

4

2 回答 2

11

你是完全正确的,从某种意义上说,yyyy::xxx如果有一个名称空间yyyy和一个类yyyy在同一范围内都是可见的,那么这可能是模棱两可的。在这种情况下,只有完全限定::yyyy::xxx才能解决歧义。您的链接示例非常清楚:

// from cppreference.com
#include <iostream>
int main() {
  struct std{};
  std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
  ::std::cout << "ok\n"; // OK: ::std finds the namespace std
}

但在实践中,很难std在顶层创建冲突,因为标准库中的大多数包含都会使其失败:

#include <iostream>

struct std {      // OUCH: error: ‘struct std’ redeclared as different kind of symbol
    int hello;  
}; 

这意味着要创建冲突,您需要定义本地类或using在另一个命名空间中引入子句。此外,没有人会(敢)调用一个类std

最后,在实践中,::yyyy::xxx阅读起来不太方便。所有这一切都解释了为什么你不会经常找到它。

补充说明

问题不std在于众所周知的问题,而在于您自己的名称空间和第三方库。在这种情况下,命名空间别名将是:::yyyy消除歧义的更好选择:

namespace foo {
    void printf() { }
}
int main() {
    foo::printf();          // ok, namespace is chose because no ambiguity
    struct foo {/*...*/ };  // creates ambiguity
    //foo::printf();        // error because struct foo is chosen by name lookup
    ::foo::printf();        // ok, but not if you  decide to move the code to be nested in another namespace
    namespace  mylib = foo ;   // or ::foo (see discussion below)
    mylib::printf();        // full flexibility :-)
}

它的优点是更高的灵活性。例如,假设您将移动代码以将其嵌套在封闭的命名空间中。使用命名空间别名,您的代码可以继续按原样工作(在最坏的情况下,只需对别名定义进行细微调整)。使用全局范围解析,您必须更改::foo将使用全局命名空间的所有语句。

于 2019-02-17T10:41:17.310 回答
0

为了保持大代码或更好的可读性或名称冲突,C++ 提供了命名空间“声明性区域”。命名空间定义只能出现在全局范围内,或嵌套在另一个命名空间中。

#Sample Code
#include <iostream>
int main() 
{
      struct std{};
      std::cout << "fail\n"; // Error: unqualified lookup for 'std' finds the struct
      ::std::cout << "ok\n"; // OK: ::std finds the namespace std
}

在上面的代码中,编译器在struct std中查找 cout ,但是在下一行中,当您使用::std::cout时,它会在全局定义的 std 类中查找cout 。

解决方案:

#include <iostream>
//using namespace std; // using keyword allows you to import an entire namespace at once. 

namespace test
{
    void cout(std::string str)
    {
       ::std::cout<<str; 
    }
}

int main() 
{
    cout("Hello");//'cout' was not declared in this scope
    ::test::cout("Helloo ") ;
    ::std::cout<<"it is also ok\n";
}

或者这样使用,只是为了更好的可读性

##
using namespace test;
int main() 
{
    cout("Hello");//'cout' was not declared in this scope
    cout("Helloo ") ;
    ::std::cout<<"it is also ok\n";
}
于 2019-02-17T12:55:02.487 回答