我的编码风格包括以下习语:

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是verbose和/或模板化的时候。

事实上,super是在Java和c#中实现的(在c#中,它被称为“base”,除非我错了)。但是c++缺少这个关键字。

我的问题是:

这种typedef的使用在你工作的代码中是超级常见/罕见/从未见过吗? 这种typedef的使用是超级Ok(也就是说,你看到强烈或不那么强烈的理由不使用它)? “super”应该是一个好东西吗?它应该在c++中标准化吗?或者通过类型定义来使用已经足够了吗?

编辑:Roddy提到的事实类型定义应该是私有的。这意味着任何派生类在不重新声明它的情况下都不能使用它。但我猜它也会阻止super::super链接(但谁会为它哭泣呢?)

编辑2:现在,在大量使用“super”几个月后,我完全同意罗迪的观点:“super”应该是私人的。


当前回答

在从Turbo Pascal迁移到c++之后,我曾经这样做是为了有一个等效的Turbo Pascal“inherited”关键字,它以相同的方式工作。然而,在用c++编程了几年之后,我就不再这么做了。我发现我不是很需要它。

其他回答

我总是用“inherited”而不是super。(可能是由于Delphi背景),我总是使它私有,以避免当“继承”被错误地从一个类中省略,但一个子类试图使用它时的问题。

class MyClass : public MyBase
{
private:  // Prevents erroneous use by other classes.
  typedef MyBase inherited;
...

我创建新类的标准“代码模板”包括typedef,所以我很少有机会不小心忽略它。

我不认为链式的“super::super”建议是一个好主意——如果您这样做,您可能会非常困难地绑定到一个特定的层次结构,并且更改它可能会严重破坏东西。

在从Turbo Pascal迁移到c++之后,我曾经这样做是为了有一个等效的Turbo Pascal“inherited”关键字,它以相同的方式工作。然而,在用c++编程了几年之后,我就不再这么做了。我发现我不是很需要它。

为什么c++不支持“super”关键字的简单答案是。

DDD(死亡之钻)问题。

在多重继承中。编译器会混淆哪个是超类。

那么哪个超类是D的超类呢??“Both”不能是解决方案,因为“super”关键字是指针。

这样做的一个问题是,如果你忘记(重新)为派生类定义super,那么任何对super::的调用都可以编译,但可能不会调用想要的函数。

例如:

class Base
{
public:  virtual void foo() { ... }
};

class Derived: public Base
{
public:
    typedef Base super;
    virtual void foo()
    {
        super::foo();   // call superclass implementation

        // do other stuff
        ...
    }
};

class DerivedAgain: public Derived
{
public:
    virtual void foo()
    {
        // Call superclass function
        super::foo();    // oops, calls Base::foo() rather than Derived::foo()

        ...
    }
};

(正如Martin York在对这个答案的评论中指出的,这个问题可以通过将类型定义为private而不是public或protected来消除。)

我不知道这种情况是否罕见,但我肯定也做过同样的事情。

正如前面所指出的,当一个类使用多重继承时,这部分语言本身的困难就出现了。