如何设置表示接口的类?这只是一个抽象基类吗?


当前回答

如果您只需要接口的静态绑定(没有虚拟的,没有接口类型本身的实例,接口仅作为指南):

#include <iostream>
#include <string>

// Static binding interface
// Notice: instantiation of this interface should be usefuless and forbidden.
class IBase {
 protected:
  IBase() = default;
  ~IBase() = default;

 public:
  // Methods that must be implemented by the derived class
  void behaviorA();
  void behaviorB();

  void behaviorC() {
    std::cout << "This is an interface default implementation of bC().\n";
  };
};

class CCom : public IBase {
  std::string name_;

 public:
  void behaviorA() { std::cout << "CCom bA called.\n"; };
};

class CDept : public IBase {
  int ele_;

 public:
  void behaviorB() { std::cout << "CDept bB called.\n"; };
  void behaviorC() {
    // Overwrite the interface default implementation
    std::cout << "CDept bC called.\n";
    IBase::behaviorC();
  };
};

int main(void) {
  // Forbid the instantiation of the interface type itself.
  // GCC error: ‘constexpr IBase::IBase()’ is protected within this context
  // IBase o;

  CCom acom;
  // If you want to use these interface methods, you need to implement them in
  // your derived class. This is controled by the interface definition.
  acom.behaviorA();
  // ld: undefined reference to `IBase::behaviorB()'
  // acom.behaviorB();
  acom.behaviorC();

  CDept adept;
  // adept.behaviorA();
  adept.behaviorB();
  adept.behaviorC();
  // adept.IBase::behaviorC();
}

其他回答

使用纯虚拟方法创建类。通过创建另一个重写这些虚拟方法的类来使用该接口。

纯虚拟方法是定义为虚拟并分配给0的类方法。

class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Child : public IDemo
{
    public:
        virtual void OverrideMe()
        {
            // do stuff
        }
};

我还是C++开发的新手。我从Visual Studio(VS)开始。

然而,似乎没有人提到VS(.NET)中的__interface。我不太确定这是否是声明接口的好方法。但它似乎提供了额外的强制执行(文件中提到)。这样就不必显式指定虚拟TYPE Method()=0;,因为它将被自动转换。

__interface IMyInterface {
   HRESULT CommitX();
   HRESULT get_X(BSTR* pbstrName);
};

然而,我不使用它,因为我担心跨平台编译兼容性,因为它只在.NET下可用。

如果有人对此感兴趣,请分享。:-)

谢谢

在C++11中,您可以轻松避免完全继承:

struct Interface {
  explicit Interface(SomeType& other)
  : foo([=](){ return other.my_foo(); }), 
    bar([=](){ return other.my_bar(); }), /*...*/ {}
  explicit Interface(SomeOtherType& other)
  : foo([=](){ return other.some_foo(); }), 
    bar([=](){ return other.some_bar(); }), /*...*/ {}
  // you can add more types here...

  // or use a generic constructor:
  template<class T>
  explicit Interface(T& other)
  : foo([=](){ return other.foo(); }), 
    bar([=](){ return other.bar(); }), /*...*/ {}

  const std::function<void(std::string)> foo;
  const std::function<void(std::string)> bar;
  // ...
};

在这种情况下,接口具有引用语义,即您必须确保对象比接口更长寿(也可以创建具有值语义的接口)。

这些类型的接口有其优点和缺点:

它们比基于继承的多态性需要更多的内存。它们通常比基于继承的多态性更快。在那些你知道最终类型的情况下,它们要快得多!(像gcc和clang这样的一些编译器在没有/继承自具有虚拟函数的类型的类型中执行更多的优化)。

最后,继承是复杂软件设计中所有邪恶的根源。在Sean Parent的《基于价值语义和概念的多态性》(强烈推荐,此处解释了该技术的更好版本)中,研究了以下案例:

假设我有一个应用程序,在其中我使用MyShape界面处理我的形状:

struct MyShape { virtual void my_draw() = 0; };
struct Circle : MyShape { void my_draw() { /* ... */ } };
// more shapes: e.g. triangle

在应用程序中,您可以使用YourShape界面对不同的形状执行相同的操作:

struct YourShape { virtual void your_draw() = 0; };
struct Square : YourShape { void your_draw() { /* ... */ } };
/// some more shapes here...

现在,假设您想使用我在您的应用程序中开发的一些形状。从概念上讲,我们的形状具有相同的界面,但要使我的形状在您的应用程序中工作,您需要按如下方式扩展我的形状:

struct Circle : MyShape, YourShape { 
  void my_draw() { /*stays the same*/ };
  void your_draw() { my_draw(); }
};

首先,修改我的形状可能根本不可能。此外,多重继承导致了意大利面代码的发展(假设第三个项目使用TheirShape接口……如果他们也调用绘图函数my_draw会发生什么?)。

更新:有一些关于非继承多态性的新参考:

Sean Parent的继承权是恶语的基础。Sean Parent的价值语义和基于概念的多态性谈话。Pyry Jahkola的无继承多态性演讲和poly库文档。Zach Laine的实用类型擦除:用优雅的设计模式解决OOP问题。Andrzej的C++博客-类型Erasure第i、ii、iii和iv部分。ConceptC中混合对象和概念的运行时多态泛型编程++Boost.TypeErasure文档Adobe Poly文档Boost.Any,std::任何提案(修订版3),Boost.Spirit::hold_Any。

以上都是好答案。还有一件事你应该记住——你也可以有一个纯粹的虚拟析构函数。唯一的区别是你仍然需要实现它。

困惑的


    --- header file ----
    class foo {
    public:
      foo() {;}
      virtual ~foo() = 0;

      virtual bool overrideMe() {return false;}
    };

    ---- source ----
    foo::~foo()
    {
    }

你想这样做的主要原因是,如果你想提供接口方法,就像我所说的那样,但让重写它们成为可选的。

要使类成为接口类,需要一个纯虚方法,但所有的虚方法都有默认实现,因此唯一剩下的方法就是析构函数。

在派生类中重新实现析构函数根本没什么大不了的——我总是在派生类里重新实现一个析构函数,不管是虚拟的还是非虚拟的。

除了C#/Java中的抽象基类之外,您还有一个特殊的接口类型类别,这是因为C#/Java不支持多重继承。

C++支持多重继承,因此不需要特殊类型。没有非抽象(纯虚拟)方法的抽象基类在功能上等同于C#/Java接口。