gpt4 book ai didi

c++ - 在父类中实现抽象类成员

转载 作者:太空狗 更新时间:2023-10-29 20:30:24 24 4
gpt4 key购买 nike

是否可以在 C++ 中使用从另一个父类继承的成员来实现抽象基类?

它在 C# 中有效,所以我尝试在 C++ 中执行:

// Virtual destructors omitted for brevity

class ITalk
{
public:
virtual void SayHi() = 0;
};

class Parent
{
public:
void SayHi();
};

class Child : public Parent, public ITalk
{
};

void Parent::SayHi()
{
std::printf("Hi\n");
}

虽然我的编译器不太喜欢它:

ITalk* lChild = new Child(); // You idiot, Child is an abstract class!
lChild->SayHi();

我不能添加 public ITalkParent 类,因为“基类‘ITalk’已经是‘家长’。”我可以移动 public ITalkParent 类,但在我的特定情况下,这会使很多事情复杂化。

最佳答案

不,因为您真正拥有的是两个相互不了解的基类。

Italk    Parent / \       / \  |         |  +---------+       |     Child

If Parent and Italk had two variables named i, there'd be two instances of "i", ITalk::i and Parent::i. To access them you'd have to fully qualify which one you wanted.

The same is true of methods, lChild has two methods called SayHi and you need to clarify which one you mean when calling SayHi because the multiple inheritance has made it ambiguous.

You have Parent's SayHi

lChild->Parent::SayHi();

和 Italk 的 SayHi:

lChild->ITalk::SayHi(); 

后者是纯虚的,因为它的抽象需要在Child本地覆盖。为了满足这一点,您需要定义

Child::SayHi();

现在调用 SayHi 时将隐藏 Parent::SayHi() 而不将其限定在类中:

lChild->SayHi() //parent's now hidden, invoke child's

当然 Child::SayHi() 可以调用 Parent::SayHi():

void Child::SayHi()
{
Parent::SayHi();
}

这将解决您的问题。

关于c++ - 在父类中实现抽象类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167558/

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