【发布时间】:2011-09-21 15:38:26
【问题描述】:
我对虚拟基类的工作方式有点困惑。特别是,我想知道如何调用基类的构造函数。我写了一个例子来理解它:
#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”。所以现在我很困惑。理解 A 的构造函数如何被调用的规则是什么?
【问题讨论】:
-
结构 F 的最后一种情况在那个问题中没有讨论,尽管也许我应该从答案中理解它。
标签: c++ virtual multiple-inheritance base-class