学生类,数据成员包括学号(公有)、姓名(保护)、年龄(私有)、学生数(静态)。学生数用来统计构造出来的学生对象数量
课代表类,继承自学生类,数据包括负责课程编号(公有)、课程评分(公有)
要求使用构造初始化符表“:”的形式进行构造,每个类又相关数据的输出显示函数
在主函数中构造对象并输出显示相关数据
#include<iostream>
using namespace std;
//定义学生类
class Student {
public:
Student(char* n, int i, int a) {
char *p = new char[strlen(n) + 1];
name = p;
strcpy_s(name, strlen(n) + 1, n);
total_num++;
id = i;
age = a;
}
//获取各个成员变量
static int GetTotal() { return total_num; }
char* GetName() { return name; }
int GetAge() { return age; }
int GetId() { return id; }
//显示学生信息
void Display() {
cout << "Name: " << name << endl;
cout << "Id : " << id << endl;
cout << "Age : " << age << endl << endl;
}
int id;
protected:
char *name;
private:
static int total_num;
int age;
};
//初始化静态成员变量
int Student::total_num = 0;
//定义课代表类
class Lesson_rep :public Student {
public:
Lesson_rep(char* n, int i, int a, int l, double s) :Student(n, i, a) {
lesson_num = l;
score = s;
}
int lesson_num;
double score;
//显示课代表信息
void Display() {
cout << "Name: " << GetName() << endl;
cout << "Id : " << GetId() << endl;
cout << "Age : " << GetAge() << endl;
cout << "Lesson Number: " << lesson_num << endl;
cout << "Lesson Score : " << score << endl << endl;
}
};
int main() {
Student stu1("Mike", 112268, 19);
Student stu2("Eve", 113980, 18);
Student stu3("Michael", 127923, 17);
Lesson_rep stu4("Jack", 118888, 20, 666666, 87.62);
cout << "Information about Michael:" << endl;
stu3.Display();
cout << "Information about Jack:" << endl;
stu4.Display();
cout << "Total Number of Students: " << Student::GetTotal() << endl;
}
运行结果:
Information about Michael:
Name: Michael
Id : 127923
Age : 17
Information about Jack:
Name: Jack
Id : 118888
Age : 20
Lesson Number: 666666
Lesson Score : 87.62
Total Number of Students: 4
请按任意键继续. . .