在父类中实现抽象类成员 [英] Implementing abstract class members in a parent class

查看:21
本文介绍了在父类中实现抽象类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它在 C# 中工作,所以我尝试在 C++ 中这样做:

//为简洁起见省略了虚拟析构函数类ITalk{民众:虚拟无效 SayHi() = 0;};班级家长{民众:void SayHi();};class Child : public Parent, public Italk{};void Parent::SayHi(){std::printf("嗨
");}

不过我的编译器并不喜欢它:

ITalk* lChild = new Child();//你这个白痴,Child 是一个抽象类!lChild->SayHi();

我不能添加public ITalkParent类,因为基类‘ITalk’已经是‘父母’."我可以移动 public ITalkParent 类,但在我的特定场景中,这会使很多事情复杂化.

解决方案

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

<前>Italk 家长//||+---------+|孩子

如果 Parent 和 Italk 有两个名为 i 的变量,就会有两个i"的实例,ITalk::i 和 Parent::i.要访问它们,您必须完全限定您想要的那个.

方法也是一样,lChild有两个方法叫SayHi,调用SayHi的时候需要说明是哪一个,因为多重继承导致歧义.

你有父母的 SayHi

lChild->Parent::SayHi();

和 Italk 的 SayHi:

lChild->ITalk::SayHi();

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

Child::SayHi();

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

lChild->SayHi()//父现在隐藏,调用子的

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

void Child::SayHi(){父::说嗨();}

这将解决您的问题.

Is it possible to implement an abstract base class with members inherited from another parent class in C++?

It works in C#, so I tried doing it in 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
");
}

My compiler didn't really like it though:

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

I can't add public ITalk to the Parent class because "base-class 'ITalk' is already a base-class of 'Parent'." I could move public ITalk up to the Parent class, but in my particular scenario that complicates a lot of things.

解决方案

No because what you really have is two base classes without any knowledge of each other.

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();

and Italk's SayHi:

lChild->ITalk::SayHi(); 

The latter is pure virtual and because its abstract needs to be overridden locally in Child. To satisfy this you'll need to define

Child::SayHi();

Which would now hide Parent::SayHi() when invoking SayHi without scoping it to the class:

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

Of course Child::SayHi() could call Parent::SayHi():

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

which would solve your problem.

这篇关于在父类中实现抽象类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆