C++:共同祖先和 interface/prototype 是 C++ class 的互斥特性吗?

C++: Are common ancestry and an interface/prototype mutually exclusive features of a C++ class?

在C++中,继承一个共同的祖先和继承一个接口(并且需要在派生的classes中定义一个方法)是否需要多重继承?例如。我是否必须执行以下操作(而不是合并 MyInterfaceParentClass):

class MyInterface;
class ParentClass;
class DerivedClass1;
class DerivedClass2;
class SomeOtherType;
class YetAnotherType;

class MyInterface {
  public:
    //  Must be defined in all derived classes
    virtual SomeOtherType my_common_fxn(...) = 0;
    ...
};

class ParentClass {
  private:
    //  Common ancestor
    YetAnotherType _useful_member;
}

class DerivedClass1 : MyInterface, ParentClass {
  public:
    // Do some things with _useful_member, using approach #1
    SomeOtherType my_common_fxn(...);
    ...
}

class DerivedClass2 : MyInterface, ParentClass {
  public:
    // Do some things with _useful_member, using approach #2
    SomeOtherType my_common_fxn(...);
    ...
}

void fxn_or_method_using(ParentClass);

是否可以(优雅地)将 MyInterfaceParentClass 的功能合并为一个 class? (我认为 MyInterface 是一个 ABC,我不能将此类型用作 fxn_or_method_using 的参数。)

如果这是重复的,请提前致歉 - 我已经搜索过,但 none 现有的 C++ 问题似乎是一致的。 Q 的 and/or A 可能超出了我(未受过训练的)的头脑。

没有。您可以在 C++ 中混合来自同一个 class 的虚拟和纯虚拟和具体继承,没有任何问题。

class baseClass{

public:
  blah1(){
  //stuff
}
  virtual blah2();

  virtual blah3() = 0;

};

class derivedClass : baseClass
{


};

你的继承模型没有问题。

但是在 C++ 中,多态性需要指针或引用。您的 fxn_or_method_using 按值获取其参数。这有几个问题。它导致切片,它阻止多态函数调用,并且它不能用于抽象类型,因为你不能创建它们的实例。

如果您将 fxn_or_method_using 更改为通过引用而不是值来获取其参数,那么您可以根据需要将其声明为引用 MyInterface。所有的缺点都消失了,你得到了你想要的多态行为。