具有子类的类的纯接口

时间:2013-08-09 12:56:26

标签: c++ interface

让我们假设您想要创建Derived类的接口,它看起来像这样:

class Derived : public Base
{
   public:
      foo();
}

class Base
{
   public:
      tii();
      //many other methods
}

你会如何做界面?如何使Base :: tii可见(以及其他方法)到这个新界面?

class IDerived
{
   public:
      virtual foo() = 0;
      // should I declare here tii() as a pure virtual function?
      // but by doing it now there is ambiguity!
}

什么是好策略?

新的Derived类应该如下所示....

class Derived : public Base, public IDerived
{
    //implement the real thing    
}

2 个答案:

答案 0 :(得分:2)

您的示例是向后做事:接口应该使用所有纯虚方法独立于任何具体类定义:

class IDerived
{
   public:
      virtual void foo() = 0;
      virtual ~IDerived() {} // don't forget to include a virtual destructor
}

具体类将从界面公开派生:

class Derived : public Base, public IDerived
{
   public:
      void foo();
}

如果您希望IDerived也声明Derived继承自Base的方法,您可以通过调用继承的实现Derived显式实现该方法:

class Derived : public Base, public IDerived
{
   public:
      void foo();
      void bar() { Base::bar(); } 
}

答案 1 :(得分:1)

在前面,我不喜欢接口(它们是由除c ++以外的其他语言种植的)。 无论如何,如果你有一个,它应该是完整的:因此将'tii()作为纯虚函数'。要解决冲突,请在'Derived'中重写该函数(转发到Base :: tii)。