建立全局和局部对象时,不同的构造函数和析构函数的调用顺序

#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对象。


猜你喜欢

转载自blog.csdn.net/w3071206219/article/details/52723053
今日推荐