问题描述
是否可以实现一个抽象基类,其成员继承自C ++中的另一个父类?
它在C#中工作,我试着在C ++中做:
//虚拟析构函数为简洁起见省略
class ITalk
{
public:
virtual void SayHi()= 0;
};
class Parent
{
public:
void SayHi();
};
class Child:public Parent,public ITalk
{
};
void Parent :: SayHi()
{
std :: printf(Hi\\\
);
}
我的编译器不太喜欢:
ITalk * lChild = new Child(); //你白痴,孩子是一个抽象类!
lChild-> SayHi();
我不能添加 public ITalk
到 Parent
类,因为base-class'ITalk'已经是'Parent'的基类。我可以 public ITalk
移动到 Parent
类,复杂的东西很多。
不,因为你真正有两个基类没有彼此的任何知识。
Italk父级
/ \ / \
| |
+ --------- +
|
$ b $ p如果Parent和Italk有两个变量名为i,则有两个实例i,ITalk: :i和Parent :: i。要访问它们,你必须完全限定你想要哪一个。
方法也是如此,lChild有两个方法SayHi,你需要澄清哪一个你的意思是当调用SayHi时,因为多重继承使它不明确。
您有父母的SayHi
lChild-> Parent ::打招呼();
和Italk的SayHi:
lChild-> ITalk :: SayHi();
后者是纯虚拟的,因为它的抽象需要在Child中被本地覆盖。为了满足这个需要,你需要定义
Child :: SayHi
现在,当调用SayHi而不将范围限定为类时,将隐藏Parent :: SayHi / p>
lChild-> SayHi()//父级现在隐藏,调用子级
/ pre>
当然,Child :: SayHi()可以调用Parent :: SayHi():void Child :: SayHi()
{
Parent :: 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\n"); }
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 theParent
class because "base-class 'ITalk' is already a base-class of 'Parent'." I could movepublic ITalk
up to theParent
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 / \ / \ | | +---------+ | ChildIf 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.
这篇关于在父类中实现抽象类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!