创建一个学生类student,用C++编程实现
创建一个学生类student,每个学生都有学号,姓名,年龄,专业,以student类创建3个对象,例如张三,李四王五,要求在student类中创建多个构造函数(重载),并...
创建一个学生类student,每个学生都有学号,姓名,年龄,专业,以student类创建3个对象,例如张三,李四王五,要求在student类中创建多个构造函数(重载),并将创建后的信息输出,当多个对象生命周期结束后,以析构函数的方式自动释放动态分配的空间。
展开
展开全部
代码如下:
#include <iostream>
#include <cstring>
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;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询