构造函数与析构函数问题

来源:百度知道 编辑:UC知道 时间:2024/05/18 09:01:18
#include<iostream>
#include<string>
using namespace std;
class A
{
private:
char string[20];
public:
A(char*s)
{strcpy(string,s);
cout<<"Constructor called."<<string<<endl;
}

~A()
{cout<<"Destructor called."<<string<<endl;}
};
void fun()
{
A a1("FunObject");
static A a2("StaticObject");
cout<<"In fun().\n";
}
A a3("GlobalObject");
static A a4("ExternStaticObject");
void main()
{A a5("MainObject");
cout<<"In main(),before calling fun().\n";
fun();
cout<<"In main(),after calling fun().\n";
}
请问为什么构造函数与析构函数的顺序会是那样?

首先:在VC++6.0下对象的析构顺序与创建顺序是相反的;静态成员变量的实质是全局变量。在程序结束时,才会析构静态对象。

1.首先,构造全局对象:
A a3("GlobalObject");
static A a4("ExternStaticObject");

输出:Constructor called.GlobalObject
Constructor called.ExternStaticObject
2.进入main函数,构造对象:A a5("MainObject");
输出:Constructor called.MainObject
3.cout<<"In main(),before calling fun().\n";
4.进入fun()函数,构造对象:
A a1("FunObject");
static A a2("StaticObject");
输出:Constructor called.FunObject
Constructor called.StaticObject
5.cout<<"In fun().\n";
6.fun()函数生命结束,调用析构函数 析构a1:
输出:Destructor called.FunObject
7.cout<<"In main(),after calling fun().\n";
8.main函数生命结束,调用析构函数 析构a5
输出:Destructor called.MainObject
9.整个程序结束,析构全部全局对象,析构顺序为构造的逆顺序:
输出:Destructor called.StaticObject
Destructor called.ExternStaticObject