我的编码风格包括以下成语:
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 的使用是否 super 常见/罕见/从未见过?
- 这种使用 typedef 是否 super 好(即,您是否看到了不使用它的强烈或不那么强烈的理由)?
- “super”应该是一件好事吗?它应该在 C++ 中稍微标准化,还是通过 typedef 进行这种使用已经足够了?
编辑: Roddy 提到 typedef 应该是私有(private)的。这意味着任何派生类都无法在不重新声明的情况下使用它。但我想它也会阻止 super::super 链接(但谁会为此哭泣呢?)。
编辑 2: 现在,在大量使用“super”几个月后,我完全同意 Roddy 的观点:“super”应该是私有(private)的。
最佳答案
Bjarne Stroustrup 在C++ 的设计和演变中提到,ISO C++ 标准委员会在 C++ 第一次标准化时考虑将 super
作为关键字。
Dag Bruck 提出了这个扩展,称基类为“继承的”。该提案提到了多重继承问题,并且会标记出模棱两可的用途。甚至 Stroustrup 也深信不疑。
经过讨论,Dag Bruck(是的,提出提案的人)写道,该提案是可实现的、技术上合理的、没有重大缺陷的,并且处理了多重继承。另一方面,没有足够的 yield ,委员会应该处理一个更棘手的问题。
Michael Tiemann 来晚了,然后证明 typedef 的 super 可以正常工作,使用的技术与本文中提到的相同。
所以,不,这可能永远不会标准化。
如果您没有拷贝,Design and Evolution 非常物有所值。二手拷贝的价格约为 10 美元。
关于c++ - 在 C++ 中使用 "super",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/180601/