从接口和实现C ++继承 [英] Inheriting from both an interface and an implementation C++
问题描述
我通常在发布任何内容之前尝试在这里找到答案,但我甚至不确定如何制定我的问题。
I usually try to find answers here before I post anything, but I'm not even sure how to formulate my question.
这里是我想做的...我想定义一个基本接口和一个派生接口。然后,我想实现基本接口,额外的变量和方法。最后,我想实现一个Derived类,从实现的基本接口,但也从派生接口。我不知道你,但我的头疼。
So here's what I want to do... I want to define a Base Interface, and a Derived Interface. Then, I want to implement the Base Interface, with extra variables and methods. Finally, I want to implemented a Derived class, from the implemented Base Interface BUT ALSO from the Derived Interface. I don't know about you, but my head hurts.
如果我做下面的事情,我得到歧义定义DerivedFloat代码,因为该代码看到两者来自IBase的GetBaseValue方法,通过IDerivedFloat继承,以及从Base继承的GetBaseValue。
If I do something like below, I get Ambiguous definitions under the DerivedFloat code since that code "sees" both the GetBaseValue method from the IBase, inherited through IDerivedFloat, as well as the GetBaseValue inherited from Base.
当然,必须有一种方法来派生一个类,基本实现的功能,以及确保它实现所需的IDerivedFloat方法。
Surely, there must be a way to derive a class which uses the expanded features of the Base Implementation, as well as making sure it implements the required IDerivedFloat methods.
现在...这是一个虚拟示例,显示我在概念上实现。这不是一个真实的生活示例。
Now... This is a dummy example to show what I'm conceptually trying to achieve. It's not a real life example.
template <typename VALUE_TYPE>
class IBase
{
public:
virtual VALUE_TYPE GetBaseValue() const = 0;
};
class IDerivedFloat : public IBase<FLOAT>
{
public:
virtual void SetBaseValue(const FLOAT & value) = 0;
};
// Implementation of Base
template <typename VALUE_TYPE>
class Base : public IBase<VALUE_TYPE>
{
public:
VALUE_TYPE GetBaseValue() const { return m_BaseValue; }
protected:
VALUE_TYPE m_BaseValue;
}
// Uses expanded Base AND implements IDerivedFloat
class DerivedFloat : public Base<FLOAT>, public IDerivedFloat
{
public:
void SetBaseValue(const FLOAT & value) { m_BaseValue = value };
}
推荐答案
=http://www.cprogramming.com/tutorial/virtual_inheritance.html =nofollow>虚拟继承来解决此问题:
You can use virtual inheritance to work around this problem:
class IDerivedFloat : virtual IBase<FLOAT>
{
public:
virtual void SetBaseValue(const FLOAT & value) = 0;
};
template <typename VALUE_TYPE>
class Base : virtual IBase<VALUE_TYPE>
{
public:
VALUE_TYPE GetBaseValue() const { return m_BaseValue; }
protected:
VALUE_TYPE m_BaseValue;
}
使用虚拟继承赋予派生类一个基类成员的实例,每次在类层次结构中存在一个。
Using virtual inheritance gives the derive class one instance of the base class members, instead of one from each time it exists in the class hierarchy.
这篇关于从接口和实现C ++继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!