是否可以通过继承来实现一个接口?

Is it possible to implement an interface through inheritance?

struct I { 
      virtual void foo() = 0; 
      virtual void bar() = 0;
};

struct A { 
        void foo(){};
 };
struct B: public A, public I {

     void bar(){};
};

这个伪代码应该在 C++ 中有效吗?目前,我在 link 时收到 foo() 的未定义引用错误。

如果这不起作用,请推荐一种创建接口的技术,该接口通过继承实现,如示例中所示。

这取决于你所说的 "valid" 是什么意思。您必须添加缺少的 return 类型,并可能修复一些其他语法问题,才能使其编译。

如果您的意思是 "is B a non-abstract class that correctly overrides both pure virtual functions declared in I?",那么不会。它不会覆盖 foo;继承同名函数不算重写。

如果您希望 A::foo 成为 I::foo 的实现,那么您必须在 B 中添加一个包装器以提供覆盖:

void foo() {A::foo();}  // assuming the missing return type is void
  1. 无法内联虚函数。您正在内联 A::foo() 和 B:bar()
  2. 您从 class B 中的两个路径继承 I。通过 A 和直接通过 I。您还需要在 class B 中提供 foo() 的实现。