在构造一个子类对象时,首先调用基类的构造函数,对基类成员进行初始化,然后才执行派生类的构造函数,如果这个基类仍然是一个派生类,那么继续
往上构造,知道完成为止;当释放该对象时,析构函数的执行顺序恰恰与构造函数相反。
// C++primary
//
// Created by amesty on 16/5/19.
// Copyright © 2016年 travelrely. All rights reserved.
//
#include<iostream>
using namespace std;
class B1
{
public:
B1(int i)
{
b1 = i;
cout<<"构造函数 B1."<<i<< endl;
}
~B1()
{
cout<<"析构函数 B1."<< endl;
}
void print()
{
cout<<"B1.print()"<<b1<<endl;
}
private:
int b1;
};
class B2
{
public:
B2(int i)
{
b2 = i;
cout<<"构造函数 B2."<<i<< endl;
}
~B2()
{
cout<<"析构函数 B2."<< endl;
}
void print()
{
cout<<"B2.print()"<<b2<<endl;
}
private:
int b2;
};
class B3
{
public:
B3(int i)
{
b3 = i;
cout<<"构造函数 B3."<<i<<endl;
}
~B3()
{
cout<<"析构函数 B3."<< endl;
}
int getb3()
{
return b3;
}
private:
int b3;
};
class A : public B2, public B1
{
public:
A(int i, int j, int k, int l):B1(i), B2(j), bb(k)
{
a = l;
cout<<"构造函数 A."<<a<<endl;
}
void print()
{
B1::print();
B2::print();
cout<<"A.print()"<<a<<","<<bb.getb3()<<endl;
}
~A()
{
cout<<"析构函数 A."<< endl;
}
private:
int a;
B3 bb;
};
int main()
{
A aa(1, 2, 3, 4);
aa.print();
}
构造函数 B2.2
构造函数 B1.1
构造函数 B3.3
构造函数 A.4
B1.print()1
B2.print()2
A.print()4,3
析构函数 A.
析构函数 B3.
析构函数 B1.
析构函数 B2.
Program ended with exit code: 0