明确重写

时间:2012-04-26 19:17:24

标签: c++ explicit-interface

用于C ++的msft编译器支持显式覆盖(请参阅http://msdn.microsoft.com/en-us/library/ksek8777.aspx

// could be declared __interface I1, making the public scope and pure virtual implied
// I use the more expressive form here for clarity
class I1
{
public:
  virtual void foo() = 0;
};

class I2
{
public:
  virtual void foo() = 0;
};

class C : public I1, public I2
{
public:
  virtual void I1::foo() { cout << "I1::foo\n"; }
  virtual void I2::foo() { cout << "I2::foo\n"; }
};

int main()
{
  C c;
  static_cast<I1*>(&c)->foo();
  static_cast<I2*>(&c)->foo();

  cin.get();
}

但是gcc不喜欢这个。简单的“显式覆盖”在线搜索会生成有关新关键字override的信息。这不一定与我要找的东西有关。这个功能是否在c ++ 11(每个规范)中以某种其他方式支持,或者至少在gcc中以某种方式支持?

注意:一个可接受的答案可能是一个黑客 - 只要它与问题的精神相同,而不是解决不同问题的新设计。

1 个答案:

答案 0 :(得分:3)

我认为唯一的方法是通过实现功能的中间类:

class Impl1 : public I1 {
public:
    void foo() { cout << "I1::foo\n"; }
};

class Impl2 : public I2 {
public:
    void foo() { cout << "I2::foo\n"; }
};

class C : public Impl1, public Impl2
{
};

当然,一旦这些功能需要访问C的成员,这会使它变得更加复杂 - 他们不能,成员需要以复杂的方式传递。

顺便说一下,不需要指针;你可以使用参考文献:

int main()
{
    C c;
    static_cast<I1&>(c).foo();
    static_cast<I2&>(c).foo();
}

(或使用明确的资格认证,完全避免虚拟派遣:)

c.Impl1::foo();
c.Impl2::foo();