#include #include using namespace std;

class Student{ private: char* pname; int score; public: Student():score(0){ pname=new char[5]; strcpy(pname,'None'); cout<<'construct None'<<endl; } Student(char* name,int sc):score(sc){ pname=new char[strlen(name)+1]; strcpy(pname,name); cout<<'construct ''<<name<<'''<<endl; } Student(const Student& s){ pname=new char[strlen(s.pname)+1]; strcpy(pname,s.pname); score=s.score; cout<<'copy ''<<s.pname<<'''<<endl; } ~Student(){ cout<<'destruct ''<<pname<<'''<<endl; delete[] pname; } void Disp(){ cout<<pname<<' '<<score<<endl; } };

int main(){ char name[20]; int score; cin>>name>>score; Student s1, s2(name, score), s3(s2); s1.Disp(); s2.Disp(); s3.Disp(); Student s4=s3; s4.Disp(); return 0; }

C++ 学生类设计与实现:动态内存分配、构造函数、析构函数、拷贝构造函数

原文地址: https://www.cveoy.top/t/topic/m7tu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录