基类子类子对象的构造与析构顺序

#include <iostream>
using namespace std;

class B1 {
public:
    B1(int i) {
        b1 = i;
        cout << "constructor B1. " << i << endl;
    }
    ~B1() {
        cout << "destructor B1" << endl;
    }
    void print(){
        cout << b1 << endl;
    }
private:
    int b1;
};
class B2 {
public:
    B2(int i) {
        b2 = i;
        cout << "constructor B2. " << i << endl;
    }
    ~B2() {
        cout << "destructor B2" << endl;
    }
    void print() {
        cout << b2 << endl;
    }
private:
    int b2;
};

class B3 {
public:
    B3(int i) {
        b3 = i;
        cout << "constructor B3. " << i << endl;
    }
    ~B3() {
        cout << "destructor B3" << endl;
    }
    int getb3() {
        return b3;
    }
private:
    int b3;
};

class A:public B2, public B1 { // crutial.
public:
    A(int i, int j, int k, int l): B1(i), B2(j), bb(k) {
        a = l;
        cout << "constuctor A" << endl;
    };
    ~A() {
        cout << "destructor A" << endl;
    }
    void print() {
        B1::print();
        B2::print();
        cout << a << "," << bb.getb3() << endl;
    }
private:
    int a;
    B3 bb;
};

int main() {
    A aa(1, 2, 3, 4);
    aa.print();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值