虚拟基类和初始化列表 [英] virtual base class and initialization lists
问题描述
可能重复:
gcc c ++虚拟继承问题
p>
我想知道当使用来自虚拟基类的多重继承时,编译器如何处理不同的初始化值。考虑臭名昭着的钻石的恐惧继承计划:
基本
/ \
/ \
D1 D2
\ /
\ /
加入
$ b b
为了避免在 Join
中有 Base
的两个副本,我使用虚拟继承 D1
和 D2
(参见例如此处)。现在,让 Base
不是抽象的,但有一个成员字段,它在其构造函数中初始化:
class Base {
public:
Base(int x_){x = x_;};
virtual〜Base(){};
public:
int x;
};
class D1:public virtual Base {
public:
D1():Base(1){};
virtual〜D1(){};
};
class D2:public virtual Base {
public:
D2():Base(2){};
virtual〜D2(){};
};
类加入:public D1,public D2 {
public:
Join(){};
〜Join(){};
};
int main()
{
加入j;
cout<< j.x<< endl;
return 0;
}
输出是1,2还是编译器依赖? / p>
它不编译。虚拟基址由最小的导出类 Join
初始化。 加入
未显式初始化 Base
,但 Base
[它也不会编译,因为类的定义需要以;
但我认为这是一个错字。 main
也应该返回 int
,我假设 jx
是 j-> x
的拼写错误。]
Possible Duplicate:
gcc c++ virtual inheritance problem
Hi all,
I'm wondering about how the compiler would handle different initialization values when using multiple inheritance from a virtual base class. Consider the notorious 'diamond of dread' inheritance scheme:
Base
/ \
/ \
D1 D2
\ /
\ /
Join
In order to avoid having two copies of Base
in Join
, I use virtual inheritance for D1
and D2
(see e.g. here). Now, lets say Base
is not abstract, but has a member field, which is initialized in its constructor:
class Base {
public:
Base(int x_) {x = x_;};
virtual ~Base(){};
public:
int x;
};
class D1 : public virtual Base {
public:
D1() : Base(1) {};
virtual ~D1(){};
};
class D2 : public virtual Base {
public:
D2() : Base(2) {};
virtual ~D2(){};
};
class Join : public D1, public D2 {
public:
Join(){};
~Join(){};
};
int main()
{
Join j;
cout << j.x << endl;
return 0;
}
Will the output be 1, 2, or is it compiler-dependent?
It shoudn't compile. Virtual bases are initialized by the most derived class which is Join
. Join
doesn't explicitly initialize Base
but Base
has no accessible default constructor.
[It also won't compiler because definitions of classes need to be terminated with a ;
but I've assumed that this is a typo. main
should also return int
and I've assumed that j.x
is a typo for j->x
.]
这篇关于虚拟基类和初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!