构造函数和析构函数,具有一般函数没有的特点,在对象定义时,构造函数会自动执行,析构函数在对象生命周期结束时会自动收回资源。细读下面程序,分析程序执行结果。
#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;
}