代码如下:
#include
#include
using namespace std;
class Student {
public:
Student() {
this->id = 0;
this->name = NULL;
this->age = 0;
this->major = NULL;
}
Student(int id, const char * name) {
this->id = id;
this->name = NULL;
SetName(name);
this->age = 0;
this->major = NULL;
}
Student(int id, const char * name, int age, const char *major) {
this->id = id;
this->name = NULL;
SetName(name);
this->age = age;
this->major = NULL;
SetMajor(major);
}
~Student() {
if (this->name) {
delete this->name;
}
if (this->major) {
delete this->major;
}
}
int GetId() const {
return this->id;
}
void SetId(int id) {
this->id = id;
}
const char * GetName() const {
return this->name;
}
void SetName(const char * name) {
if (this->name) {
delete this->name;
}
int len = strnlen_s(name, 20);
this->name = new char[len + 1];
strcpy_s(this->name, len + 1, name);
}
int GetAge() const {
return this->age;
}
void SetAge(int age) {
this->age = age;
}
const char * GetMajor() const {
return this->major;
}
void SetMajor(const char * major) {
if (this->major) {
delete this->major;
}
int len = strnlen_s(major, 20);
this->major = new char[len + 1];
strcpy_s(this->major, len + 1, major);
}
private:
int id;
char * name;
int age;
char * major;
};
void PrintStudent(const Student& student)
{
cout << student.GetId() << "," << student.GetName() << "," << student.GetAge() << "," << student.GetMajor() << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Student stu1(2001, "张三", 25, "计算机应用");
PrintStudent(stu1);
Student stu2(2002, "李四");
stu2.SetAge(22);
stu2.SetMajor("美术");
PrintStudent(stu2);
Student stu3;
stu3.SetId(2003);
stu3.SetName("王五");
stu3.SetAge(20);
stu3.SetMajor("音乐");
PrintStudent(stu3);
system("pause");
return 0;
}