在设计此类时,为了让大家从运行结果中很好的看出和理解构造函数和析构函数调用的顺序,定义了两个数据成员data和type,data用于给对象编号,type用于给出是全局变量或者哪个函数的局部或静态变量。
在定义对象时,同时给出这两个参数来对对象进行初始化工作。
代码设计如下:
#include <iostream>
#include <string>
using namespace std;
class CreateAndDestroy
{
public:
CreateAndDestroy(int,string);
//构造函数
~ CreateAndDestroy( );
//析构函数
private:
int data;
string type;
};
CreateAndDestroy::CreateAndDestroy(int value,string type_name)
{
data=value;
type=type_name;
cout<<"Object "<<data<<" "<<type<<" constructor"<<endl;
}
CreateAndDestroy::~CreateAndDestroy()
{
cout<<"Object "<<data<<" "<<type<<" destructor"<<endl;
}
CreateAndDestroy obj1(1,"global"); //全局对象
CreateAndDestroy obj2(2,"global"); //全局对象
void main()
{
void create();
cout<<"(global created before main)\n";
cout<<"main begin..."<<endl;
CreateAndDestroy obj3(3,"main() local"); //局部对象
cout<<"(local automatic in main) \n";
static CreateAndDestroy obj4(4,"main() static"); //局部静态对象
cout<<"(local static in main) \n";
cout<<"call create begin,leave main.... "<<endl;
create(); //调用建立对象的函数
cout<<"call create over,return main"<<endl;
CreateAndDestroy obj5(5,"main() local"); //局部对象
cout<<"(local automatic in main) \n";
static CreateAndDestroy obj6(6,"main() static"); //局部静态对象
cout<<"(local static in main) \n";
cout<<"main end..."<<endl;
}
void create()
{
cout<<"create begin..."<<endl;
CreateAndDestroy obj7(7,"create() local"); //局部对象
cout<<"(local automatic in create) \n";
static CreateAndDestroy obj8(8,"create() static"); //局部静态对象
cout<<"(local static in create) \n";
CreateAndDestroy obj9(9,"create() local"); //局部对象
cout<<"(local automatic in create) \n";
static CreateAndDestroy obj10(10,"create() static"); //局部静态对象
cout<<"(local static in create) \n";
cout<<"create end..."<<endl;
}
运行结果如下