代码:
#include <iostream>
using namespace std;
class Data
{
public:
Data(int i):x(i)
{
cout<<"A";
}
~Data()
{
cout<<"B";
}
private:
int x;
};
class Base
{
public:
Base(int i):b1(i)
{
cout<<"C";
}
~Base()
{
cout<<"D";
}
private:
int b1;
};
class Derived:public Base
{
public:
Derived (int i,int j):Base(i),d1(j)
{
cout<<"E";
}
~Derived()
{
cout<<"F";
}
private:
Data d1;
};
int main()
{
Derived obj(1,2);
return 0;
}
运行结果:
学习心得:
Base是Derived的基类,Derived是Base的派生类,所以调用结构函数,先调用Base类,输出”C“,因为d1是Date类,所以再输出”A“,然后在输出”E“,调用析构函数,先调用派生类的析构函数,输出”F“,先结构的后析构,所以再输出“B”和“F”。