[英]C++ A multiple inheritance pproblem with pure virtual functions
I have produced a minimal example to replicate the problem I am seeing with a more complex class hierarchy structure:我已经制作了一个最小的例子来复制我看到的具有更复杂的类层次结构的问题:
#include <string>
#include <iostream>
class A
{
protected:
virtual
~A() = 0;
};
inline
A::~A() {}
class B : public A
{
public:
virtual
~B()
{
}
std::string B_str;
};
class BB : public A
{
public:
virtual
~BB()
{
}
std::string BB_str;
};
class C : public A
{
protected:
virtual
~C()
{
}
virtual
void Print() const = 0;
};
class D : public B, public BB, public C
{
public:
virtual
~D()
{
}
};
class E : public C
{
public:
void Print() const
{
std::cout << "E" << std::endl;
}
};
class F : public E, public D
{
public:
void Print_Different() const
{
std::cout << "Different to E" << std::endl;
}
};
int main()
{
F f_inst;
return 0;
}
Compiling with g++ --std=c++11 main.cpp
produces the error:使用
g++ --std=c++11 main.cpp
编译会产生错误:
error: cannot declare variable ‘f_inst’ to be of abstract type ‘F’
F f_inst;
note: because the following virtual functions are pure within ‘F’:
class F : public E, public D
^
note: virtual void C::Print() const
void Print() const = 0;
^
So the compiler thinks that Print()
is pure virtual.所以编译器认为
Print()
是纯虚拟的。
But, I have specified what Print()
should be in class E
.但是,我已经在
class E
指定了Print()
应该是什么。
So, I've misunderstood some of the rules of inheritance.所以,我误解了一些继承规则。
What is my misunderstanding, and how can I correct this problem?我的误解是什么,我该如何纠正这个问题?
Note: It will compile if I remove the inheritance : public D
from class F
.注意:如果我删除继承
: public D
from class F
,它将编译。
Currently your F
is derived from C
in two different ways.目前,您的
F
以两种不同的方式从C
派生而来。 This means that an F
object has two separate C
bases, and so there are two instances of C::Print()
.这意味着
F
对象有两个独立的C
基础,因此有两个C::Print()
实例。
You only override the one coming via E
currently.您只覆盖当前通过
E
来的那个。
To solve this you must take one of the following options:要解决此问题,您必须采用以下选项之一:
D
, either by implementing D::Print()
or F::Print()
D::Print()
或F::Print()
来覆盖通过D
来的那个Print
non-purePrint
不纯C
base.C
基础。 For the latter option, the syntax adjustments would be:对于后一个选项,语法调整将是:
class E : virtual public C
and和
class D : public B, public BB, virtual public C
This means that D
and E
will both have the same C
instance as their parent, and so the override E::Print()
overrides the function for all classes 'downstream' of that C
.这意味着
D
和E
都将具有与其父级相同的C
实例,因此覆盖E::Print()
覆盖该C
'下游'的所有类的函数。
For more information , look up "diamond inheritance problem".有关更多信息,请查找“钻石继承问题”。 See also Multiple inheritance FAQ
另见多重继承常见问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.