为什么命名空间中的某些函数可以在没有命名空间作用域前缀的情

syp*_*lex 7 c++

命令空间中的函数是否只能通过使用命名空间作用域或using指令来访问?

我遇到一个问题,在命名空间内定义的某些函数可以访问该命名空间的OUTSIDE.我相信应该有一个编译器错误,但我没有在我尝试过的三个不同的编译器中得到一个(VS.NET 2003,VS2010和GCC 4).

这是代码:

namespace N{
  typedef struct _some_type *some_type;
  struct some_struct { int x; };
  void A(void);
  void B(int);
  void C(some_type*);
  void D(some_type);
  void E(struct some_struct);
}

using N::some_type;
using N::some_struct;

void TestFunction()
{
  some_type foo;
  some_struct s;

  N::A();         //should compile (and does on VS2003, VS2010, and GCC 4.1.2)
  ::A();          //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)
  A();            //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)

  N::B(0);        //should compile (and does on VS2003, VS2010, and GCC 4.1.2)
  ::B(0);         //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)
  B(0);           //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)

  N::C(&foo);     //should compile (and does on VS2003, VS2010, and GCC 4.1.2)
  ::C(&foo);      //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)
  C(&foo);        //shouldn't compile (but does on VS2003, VS2010, and GCC 4.1.2) -- problem!

  N::D(foo);      //should compile (and does on VS2003, VS2010, and GCC 4.1.2)
  ::D(foo);       //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)
  D(foo);         //shouldn't compile (but does on VS2003, VS2010, and GCC 4.1.2) -- problem!

  N::E(s);        //should compile (and does on VS2003, VS2010, and GCC 4.1.2)
  ::E(s);         //shouldn't compile (and doesn't on VS2003, VS2010, and GCC 4.1.2)
  E(s);           //shouldn't compile (but does on VS2003, VS2010, and GCC 4.1.2) -- problem!
}
Run Code Online (Sandbox Code Playgroud)

如果不使用N ::前缀,则不能访问任何函数,但C,D和E是出于某种未知原因.我最初认为这是一个编译器错误,但因为我在多个编译器中看到这个,它让我怀疑发生了什么.

Jim*_*wis 11

我想你正在看到Koenig查找的效果.在你的榜样,foos在命名空间中定义的类型N.您调用例程C,DE使用这些类型的参数,因此N搜索命名空间以解析这些函数调用.

  • 旁注:添加括号,即`(C)(&foo)`将阻止依赖于参数的查找. (3认同)