鉴于using
没有继承类范围内的声明,这可能会起作用。该名称仅在该类声明内或嵌套类的声明内有效。但我认为这有点用一个应该更大的想法来重载一个类的概念。
在 Java 和 Python 中,单个文件以特殊方式处理。您可以拥有import
将来自其他命名空间的名称注入文件的声明。这些名称(嗯,不完全是 Python,但这里解释起来太复杂了)只在该文件中可见。
对我来说,这种能力不依赖于类声明,而是赋予它自己的范围。如果有意义的话,这将允许在多个类声明中使用注入的名称,甚至在函数定义中使用。
这是我更喜欢的一个想法,因为它允许这些事情,同时仍然为您提供使用声明的类级别的好处:
using {
// A 'using' block is a sort of way to fence names in. The only names
// that escape the confines of a using block are names that are not
// aliases for other things, not even for things that don't have names
// of their own. These are things like the declarations for new
// classes, enums, structs, global functions or global variables.
// New, non-alias names will be treated as if they were declared in
// the scope in which the 'using' block appeared.
using namespace ::std;
using ::mynamespace::mytype_t;
namespace mn = ::mynamespace;
using ::mynamespace::myfunc;
class AClass {
public:
AClass(const string &st, mytype_t me) : st_(st), me_(me) {
myfunc(&me_);
}
private:
const string st_;
mn::mytype_t me_;
};
// The effects of all typedefs, using declarations, and namespace
// aliases that were introduced at the level of this block go away
// here. typedefs and using declarations inside of nested classes
// or namespace declarations do not go away.
} // end using.
// Legal because AClass is treated as having been declared in this
// scope.
AClass a("Fred", ::mynamespace::mytype_t(5));
// Not legal, alias mn no longer exists.
AClass b("Fred", mn::mytype_t);
// Not legal, the unqualified name myfunc no longer exists.
AClass c("Fred", myfunc(::mynamespace::mytype_t(5));
这类似于为函数中的局部变量声明一个块。但是在这种情况下,您声明了一个非常有限的范围,您将在其中更改名称查找规则。