我了解在头文件中放置using
声明可能会遇到的问题,所以我不想这样做。 相反,我尝试将 using
(或 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
在实际代码中,命名空间的名称通常更长且令人烦恼,这不是我可以改变的。
有人能解释一下为什么这不合法吗?或者(更好的是)是否有解决方法?