为什么我不能在类声明中放入"using"声明?

Dan*_*Dan 18 c++ namespaces using compiler-errors header

我理解当你using在头文件中放入一个声明时可以遇到的麻烦,所以我不想这样做.相反,我试图将using(或a namespace foo =)放在类声明中,以减少头文件中的重复输入.不幸的是我遇到编译错误.似乎它将是一个有用的功能.

#ifndef FOO_H
#define FOO_H

// This include defines types in namespace gee::whiz::abc::def,
// such as the class Hello.
#include "file_from_another_namespace.h"

// using namespace gee::whiz::abc::def; // BAD!

namespace x {
   namespace y {
      namespace z {

struct Foo {
    using namespace gee::whiz::abc::def; // Illegal.
    namespace other = gee::whiz::abc::def; // Illegal.

    // Foo(gee::whiz::abc::def::Hello &hello); // annoyingly long-winded

    Foo(other::Hello &hello); // better
    //...
};

} } } // end x::y::z namespace

#endif // FOO_H
Run Code Online (Sandbox Code Playgroud)

在实际代码中,命名空间名称更长,更烦人,而且我不能改变它.

任何人都可以解释为什么这不合法,或者(更好)是否有解决方法?

Fre*_*ner 24

你能做到typedef gee::whiz::abc::def::Hello Hello吗?

  • 如果它在类声明中使用,则不会. (8认同)
  • 这仍然会污染他试图避免的命名空间. (2认同)