⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 constructor_destructor_2_c_problem.cpp

📁 对于一个初涉VC++的人来书
💻 CPP
字号:

//***************************************************
// 这里由于数据成员涉及指针,没有指向确定地址,因此,
// 必须用深拷贝,否则程序编译连接没问题,但执行错误.
//***************************************************

# include <iostream.h>
# include <string.h>
# include <stdlib.h>

class Student
{
public:
	Student(char* pNam)
	{
		cout<<"Constructor "<<pNam<<endl;
		pName=new char[strlen(pNam)+1];
		if(pName==NULL)
		{
			cout<<"Can't allocate more memory,terminating.\n";
			exit(1);
		}
		strcpy(pName,pNam);
	}
	Student(Student & s)
	{
		cout<<"Constructor Copy "<<s.pName<<endl;
		pName=new char[strlen(s.pName)+1]; 
		if(pName==NULL)
		{
			cout<<"Can't allocate more memory,terminating.\n";
			exit(1);
		}
		strcpy(pName,s.pName);
	}
	~Student() //奇怪:打开析构函数后,程序不执行拷贝构造?
	{
		cout<<"Destructor "<<pName<<endl;
		delete[] pName;
	}
private:
	char* pName;
};

int main()
{
	Student s=Student("Jenny"); //用无名对象初始化对象

	cout<<"End of main()"<<endl;

	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -