C++ 学生类设计与实现:姓名、分数、构造函数、拷贝构造、析构函数
#include
class Student { private: char *pname; int score; public: Student(): pname(new char[5]), score(0) { strcpy(pname, 'None'); cout << 'construct None' << endl; }
Student(const char *name, int s): pname(new char[strlen(name)+1]), score(s) {
strcpy(pname, name);
cout << 'construct '' << pname << '''' << endl;
}
Student(const Student &s): pname(new char[strlen(s.pname)+1]), score(s.score) {
strcpy(pname, s.pname);
cout << 'copy '' << pname << '''' << endl;
}
~Student() {
cout << 'destruct '' << pname << '''' << endl;
delete [] pname;
}
void Disp() const {
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; }
原文地址: https://www.cveoy.top/t/topic/m7tB 著作权归作者所有。请勿转载和采集!