问题描述
对于虚拟基类如何工作有点困惑。特别是,我想知道如何基类的构造函数被调用。我写了一个例子来理解它:
I'm a bit confused about how virtual base classes work. In particular, I was wondering how the constructor of the base class gets called. I wrote an example to understand it:
#include <cstdio>
#include <string>
using std::string;
struct A{
string s;
A() {}
A(string t): s(t) {}
};
struct B: virtual public A{
B(): A("B"){}
};
struct C: virtual public A {};
struct D: public B, public C {};
struct E: public C, public B {};
struct F: public B {};
int main(){
D d;
printf("\"%s\"\n",d.s.c_str());
E e;
printf("\"%s\"\n",e.s.c_str());
F f;
printf("\"%s\"\n",f.s.c_str());
B b;
printf("\"%s\"\n",b.s.c_str());
}
哪些输出
""
""
""
"B"
我不知道在前两种情况会发生什么,但对于第三个,至少我期望输出是B。所以现在我只是困惑。
I wasn't sure what would happen in the first two cases, but for the third one at least I was expecting the output to be "B". So now I'm just confused. What are the rules for understanding how the constructor of A gets called?
推荐答案
总是只有一个构造函数调用,并且总是实例化的具体类。如果你在 B
'中,你需要赋予每个派生类一个构造函数来调用基类的构造函数,这是
There is always just one constructor call, and always of the actual, concrete class that you instantiate. It is your responsibility to endow each derived class with a constructor which calls the base classes' constructors if and as necessary, as you did in B
's constructor.
更新:很抱歉,缺少您的主要观点!感谢ildjarn。
Update: Sorry for missing your main point! Thanks to ildjarn.
但是, B
几乎从 A
。根据标准(FIDS中的10.1.4),对于每个指定为virtual的不同基本类,最大派生对象应包含该类型的单个基本类子对象。在你的情况下,这意味着当构建基础时,你的类 F
立即调用 A
的默认构造函数, code> B 的。
However, your B
inherits virtually from A
. According to the standard (10.1.4 in the FIDS), "for each distinct baseclass that is specified virtual, the most derived object shall contain a single base class subobject of that type". In your case this means that when constructing the base, your class F
immediately calls A
's default constructor, not B
's.
这篇关于了解虚拟基类和构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!