调用构造函数顺序(虚基类例题)

#include <iostream>
using namespace std;
class Base 
{
  public:
	  Base(int i) { cout << i; }
	  ~Base () { }
};
class Base1: virtual public Base 
{
  public:
	  Base1(int i, int j=0) : Base(j) { cout << i; }
	  ~Base1() {}
};
class Base2: virtual public Base 
{
  public:
	  Base2(int i, int j=0) : Base(j) { cout << i; }
	  ~Base2() {}
};
class Derived : public Base2, public Base1 
{
  public:
	  Derived(int a, int b, int c, int d) : mem1(a), mem2(b), Base1(c), 
                                         Base2(d), Base(a) 
    { cout << b; }
  private:
	  Base2 mem2;
	  Base1 mem1;
};
void main() { Derived objD (1, 2, 3, 4); }

void main() { Derived objD (1, 2, 3, 4); }
建立Derived类对象objD(1, 2, 3, 4),首先调用构造函数Derived(int a, int b, int c, int d) : mem1(a), mem2(b), Base1©, Base2(d), Base(a) { cout << b; }
在构造函数Derived中先调用虚基类Base的构造函数,即Base(a),将a的值1传给i,(Base(int i) { cout << i;)输出i值为1
然后根据声明顺序(class Derived : public Base2, public Base1 )Base2在前,接着调用Base2(d),将d的值传给i,(Base2(int i, int j=0) : Base(j) { cout << i; })输出i值为4,由于Base为虚基类,只有最远端派生类构造函数Derived才能调用虚基类的构造函数,该派生类的其他基类对虚基类构造函数的调用被忽略,所以系统不会做 : Base(j)
再调用Base1©, 将c的值传给i,(Base1(int i, int j=0) : Base(j) { cout << i; }),输出i值为3,同理系统不做: Base(j)
然后根据对象成员声明顺序(Base2 mem2; Base1 mem1;)先做mem2(b), 即调用构造函数Base2(int i, int j=0) : Base(j) { cout << i; },在Base2构造函数中需要先调用Base构造函数,把j=0传值给i,(Base(int i) { cout << i;)输出i值为0,再将b=2的值传给构造函数Base2中的i,输出i值为2
接着做mem1(a),同mem2(b),调用Base1构造函数时先调用Base构造函数,输出i值为0,再将,a=1的值传给构造函数Base1中的i,输出i值为1
最后做构造函数Derived中的{ cout << b; },输出b值为2
结果:14302012`

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值