多重继承 - 构造函数的规则

来源:互联网 发布:手机淘宝天天特价女装 编辑:程序博客网 时间:2024/05/18 20:47

虚基类的子类的子类在多重继承时,构造函数初始化父类的构造函数将不会将信息传给虚基类,但可以显示调用对应虚基类的构造函数来构造自身对象,从而获得一个虚基类的对象避免多重继承的冲突;如果未显示调用虚基类的构造函数,将自动调用其默认的构造函数。


C++ primer plus 6th

     14. Reusing Code in C++

           New Constructor Rules


SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other)  : Waiter(wk,p), Singer(wk,v) {}  // flawed

The problem is that automatic passing of information would pass wk to the Worker object via two separate paths (Waiter and Singer).To avoid this potential conflict, C++ disables the automatic passing of information through an intermediate class to a base class if the base class is virtual. Thus, the previous constructor will initialize the panache and voice members, but the information in the wk argument won’t get to the Waiter subobject. However, the compiler must construct a base object component before constructing derived objects;in this case, it will use the default Worker constructor.

If you want to use something other than the default constructor for a virtual base class,you need to invoke the appropriate base constructor explicitly. Thus, the constructor should look like this:

SingingWaiter(const Worker & wk, int p = 0, int v = Singer::other) : Worker(wk), Waiter(wk,p), Singer(wk,v) {}

原创粉丝点击