一、构造函数的执行顺序:
二、析构函数的执行顺序
三、用一段代码来说明
#include <iostream>
using namespace std;
class B1
{
public:
B1(int i=100){
cout<<"constructing B1 "<<i<<endl;
}
~B1(){
cout<<"destructing B1 "<<endl;
}
};
class B2
{
B1 B2memberB1;
public:
B2(int j){
cout<<"constructing B2 "<<j<<endl;
}
~B2(){
cout<<"destructing B2 "<<endl;
}
};
class B3
{
public:
B3(){
cout<<"constructing B3 *"<<endl;
}
~B3(){
cout<<"destructing B3 "<<endl;
}
};
class C
{
public:
C(int a,int b):CmemberB2(a),CmemberB1(b){}
private:
B1 CmemberB1;
B2 CmemberB2;
B3 CmemberB3;
};
int main(){
C obj(55,66);
return 0;
}
运行结果:
注意:当用new去初始化一个对象时,在程序结束时,该对象不会被自动析构!
同样用一段代码举例说明:
#include <iostream>
using namespace std;
const int N = 100;
class CStack
{
public:
CStack() { top = 0; cout << "hello"; }
~CStack() { cout << "Bye"; }
void push(int i);
int pop();
private:
int stack[N];
int top;
};
void CStack::push(int i) {
if (top == N)
{
cout << "Overflow";
return;
}
else
{
top++;
stack[top] = i;
}
}
int CStack::pop() {
int temp;
if (top == 0)
{
cout << "Underflow";
return 0;
}
else
{
temp = stack[top];
top--;
return temp;
}
}
int main() {
CStack* ptr = new CStack;
ptr->push(10);
ptr->push(50);
cout << ptr->pop() << " ";
cout << "OK!" << endl;
return 0;
}
程序结果: