gpt4 book ai didi

C++:C++ 类的共同祖先和接口(interface)/原型(prototype)是否相互排斥?

转载 作者:行者123 更新时间:2023-11-28 02:04:19 25 4
gpt4 key购买 nike

在C++中,继承共同祖先和继承接口(interface)(并且需要在派生类中定义方法)是否需要多重继承?例如。我是否必须执行以下操作(而不是合并 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 的功能合并到一个类中? (我相信由于 MyInterface 是一个 ABC,我不能将此类型用作 fxn_or_method_using 的参数。)

如果这是重复的,请提前致歉 - 我已经搜索过,但似乎没有一个现有的 C++ 问题符合要求。 Q 和/或 A 可能超出了我(未经训练的)头脑。

最佳答案

您的继承模型没有任何问题。

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

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

关于C++:C++ 类的共同祖先和接口(interface)/原型(prototype)是否相互排斥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com