我的编码风格包括以下成语:
class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
这使我能够使用“super”作为 Base 的别名,例如,在构造函数中:
Derived(int i, int j)
: super(i), J(j)
{
}
甚至在从其覆盖版本中的基类调用方法时:
void Derived::foo()
{
super::foo() ;
// ... And then, do something else
}
它甚至可以被链接起来(不过,我仍然需要找到它的用途):
class DerivedDerived : public Derived
{
public :
typedef Derived super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
void DerivedDerived::bar()
{
super::bar() ; // will call Derived::bar
super::super::bar ; // will call Base::bar
// ... And then, do something else
}
无论如何,我发现“typedef super”的使用非常有用,例如,当 Base 是冗长和/或模板化时。
事实是 super 是用 Java 和 C# 实现的(它被称为“base”,除非我错了)。但是 C++ 缺少这个关键字。
所以,我的问题:
- 在您使用的代码中,这种使用 typedef 是超级常见/罕见/从未见过的吗?
- 这种使用 typedef 是否超级好(即您是否看到了不使用它的强烈或不那么强烈的理由)?
- “超级”应该是一件好事,它是否应该在 C++ 中有所标准化,或者通过 typedef 使用它已经足够了吗?
编辑: Roddy 提到 typedef 应该是私有的。这意味着任何派生类都无法在不重新声明的情况下使用它。但我想它也会阻止 super::super 链接(但谁会为此哭泣呢?)。
编辑2:现在,在大量使用“超级”几个月后,我完全同意罗迪的观点:“超级”应该是私有的。我会两次赞成他的回答,但我想我不能。