深拷贝.cpp

来自「c++算法的很经典的一些小练习 看了 觉得还可以 给大家分享一下!」· C++ 代码 · 共 52 行

CPP
52
字号
#include<iostream.h>
#include<string.h>

class student{
	char *pName;
public:
	student();
	student(char *pname);
	student(student &s);
	~student();
	student & operator=(student &s);
};
student::student(){
	cout<<"Constructor";
	pName=NULL;
	cout<<"缺省"<<endl;
}
student::student(char*pname){
	cout<<"Constructor";
	if(pName=new char[strlen(pname)+1])strcpy(pName,pname);
	cout<<pName<<endl;
}
student::student(student &s){
    cout<<"Copy Constructor";
	if(s.pName){
		if(pName=new char[strlen(s.pName)+1])strcpy(pName,s.pName);
	}
	else pName=NULL;
	cout<<pName<<endl;
}
student::~student(){
	cout<<"Destuctor"<<pName<<endl;
	if(pName)pName[0]='\0';
	delete[]pName;
}
student&student::operator=(student&s){
	cout<<"Copy Assign operator";
	delete []pName;
	if(s.pName){
		if(pName=new char[strlen(s.pName)+1])strcpy(pName,s.pName);
	}
	else pName=NULL;
	cout<<pName<<endl;
	return *this;
}
void main(){
	student s1("范英明"),s2("沈俊"),s3;
	student s4=s1;
	s3=s2;
}

⌨️ 快捷键说明

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