#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
class student{
public:
student(int id,char* name){
cout<<"this is student(int id,char* name)----"<<endl;
this->m_id=id;
//this->m_name=name;
int len =strlen(name);
this->m_name = new char[len+1];
strcpy(this->m_name,name);
}
student(const student& s){
cout<<"this is student(const student& s)------"<<endl;
this->m_id = s.m_id;
int len =strlen(s.m_name);
this->m_name = new char[len+1];
strcpy(this->m_name,s.m_name);
}
void print(){
cout<<"id: "<<m_id<<" name: "<<m_name<<endl;
}
~student(){
cout<<"this is ~student()----"<<endl;
if(this->m_name!=NULL){
delete m_name;
this->m_name=NULL;
this->m_id=0;
}
}
student& operator=(const student& s){
cout<<"this is student& operator=(const student& s)----"<<endl;
if(this==&s){//防止自身赋值
return *this;
}
//回收自身空间
if(this->m_name!=NULL){
cout<<"recyle old addr----"<<endl;
delete[] m_name;
this->m_name=NULL;
this->m_id=0;
}
//开辟新空间
this->m_id = s.m_id;
int len =strlen(s.m_name);
this->m_name = new char[len+1];
strcpy(this->m_name,s.m_name);
}
private:
int m_id;
char* m_name;
};
void test(){
student s1(10,"zhangsan");
student s2=s1;
s2.print();
student s3(16,"li4");
s2=s3;
s2.print();
}
int main(){
/*
char *name = new char[64];
strcpy(name,"zhangsan");
student ss(1,name);
delete name;
ss.print();
*/
test();
system("pause");
return 0;
}
类的等号操作符
最新推荐文章于 2021-12-10 16:18:10 发布