信管14:构造函数和析构函数执行分析示列

构造函数和析构函数,具有一般函数没有的特点,在对象定义时,构造函数会自动执行,析构函数在对象生命周期结束时会自动收回资源。细读下面程序,分析程序执行结果。
#include <iostream>
#include <cstring>
using namespace std;

class Student{
public:
	Student(char* pName= "yale", int sId = 0)
	{
		strncpy(name,pName,40);
		name[39] = '\0';
		id = sId;
		cout <<"Constructing a student "<<pName <<endl;
	}

	Student(Student& s)                // 拷贝构造函数
	{   cout <<"Constructing copy of " <<s.name <<endl;
		strcpy(name,"copy of ");
		strcat(name,s.name);
		id = s.id;
	}

	~Student()                         //析构函数
	{ cout <<"Destructing " <<name <<endl;
	 }

private:
	char name[40];
	int id;
};

void fn(Student s)
{
	cout<<"In function fn()"<<endl;	// fn函数调用结束时,析构对象s
}



int main()
{
	Student randy("Randy",1234);	// 调用构造函数,创建对象randy
	Student wang("wang",5678);		// 调用构造函数,创建对象wang
	
	cout<<"--------------------"<<endl;
	cout<<" Calling fn()\n";
	
	fn(randy);						// 调用fn函数,参数传递时调用拷贝构造函数
	
	cout <<"Returned from fn()"<<endl
		<<"--------------------"<<endl;
	          
	system("pause");
	return 0;
}



问题:1.分析程序执行过程,分析对象构造函数和析构函数的执行时机。

            2.为什么没有看到主程序定义的对象 :randy 和wang的析构函数特执行?

           3.如果程序改成下面的结果,分析程序执行结果:

#include <iostream>
#include <cstring>
using namespace std;

class Student{
public:
	Student(char* pName= "yale", int sId = 0)
	{
		strncpy(name,pName,40);
		name[39] = '\0';
		id = sId;
		cout <<"Constructing a student "<<pName <<endl;
	}

	Student(Student& s)                // 拷贝构造函数
	{   cout <<"Constructing copy of " <<s.name <<endl;
		strcpy(name,"copy of ");
		strcat(name,s.name);
		id = s.id;
	}

	~Student()                         //析构函数
	{ cout <<"Destructing " <<name <<endl;
	 }

private:
	char name[40];
	int id;
};

void fn(Student s)
{
	cout<<"In function fn()"<<endl;	// fn函数调用结束时,析构对象s
}


void sub()
{   Student randy("Randy",1234);	// 调用构造函数,创建对象randy
	Student wang("wang",5678);		// 调用构造函数,创建对象wang
	
	cout<<"--------------------"<<endl;
	cout<<" Calling fn()\n";
	
	fn(randy);						// 调用fn函数,参数传递时调用拷贝构造函数
	
	cout <<"Returned from fn()"<<endl
		<<"--------------------"<<endl;
}


int main()
{   sub();	
	system("pause");
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值