ex7_3.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)+17]) 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<<"Destructor"<<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(void){
	student s1("范英明"),s2("沈俊"),s3;
	student s4=s1;
	s3=s2;
}

⌨️ 快捷键说明

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