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

📄 demo_copy_constructor_4.cpp

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

//***************************************************

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

class Person
{
public:
	Person(char* pN) //浅拷贝
	{
		cout<<"Constructing "<<pN<<endl;
		pName=new char[strlen(pN)+1];
		if(pName==NULL)
		{
			cout<<"Can't allocate more memory,terminating.\n";
			exit(1);
		}
		strcpy(pName,pN);
	}

	Person(Person& p) //深拷贝(这里没有深拷贝而只有浅拷贝时会出错)
	{
		cout<<"Copying "<<p.pName<<" into its own block"<<endl;
		pName=new char[strlen(p.pName)+1];
		if(pName==NULL)
		{
			cout<<"Can't allocate more memory,terminating.\n";
			exit(1);
		}
		strcpy(pName,p.pName);
	}

	~Person() //析构函数
	{
		cout<<"Destructing "<<pName<<endl;
		pName[0]='\0';
		delete pName;
//		delete[] pName;
	}

protected:
	char* pName;
};

void main()
{
	Person p1("Jenny");
	Person p2(p1); //等价于: p2=p1
}

⌨️ 快捷键说明

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