1. 程式人生 > >建立全域性和區域性物件時,不同的建構函式和解構函式的呼叫順序

建立全域性和區域性物件時,不同的建構函式和解構函式的呼叫順序

#include<iostream>
using namespace std;
void create();
class base{
	int data;
	public:
		base(int i)
		{
			data=i;
			cout<<"CONS:"<<i<<endl;
		}
		~base()
		{
			cout<<"DES:"<<data<<endl;
		}
		void show()
		{
			cout<<"data="<<data<<endl;
		}
};
int main()
{
 base third(3);
 create();
 base sixth(6);
 third.show();
 sixth.show();	
}
void create()
{
	base fourth(4);
	fourth.show();
}


當局部物件離開其作用域時,即離開其函式時,就被撤銷,從而調動其解構函式。

此外,當局部物件離開其作用域後,就無法再被訪問。例如在主函式main( )中無法訪問fourth物件,而在子函式create( )中則無法訪問third物件。