定义一个组合类课程类Lesson,其数据成员有:课号id,课程名name,任课老师teacher,选课学生s,其中学生信息定义成学生类的数组。成员函数有:AddStudent增加选课学生信息,GetPassRate计算课程的及格率,ShowInfo显示课程信息。学生类包括学号、姓名及该门课的成绩。用上述类的组合实现课程的管理。
#include <iostream>
#include <string.h>
using namespace std;
class Student{
public:
Student(){}
Student(string a,string b,float c):num(a),name(b),score(c){}
void display(); //显示学生信息函数
private:
string num; //学生学号
string name;
float score;
};
class Lesson{
public:
Lesson(string x,string y,string z):id(x),name(y),teacher(z){}
void AddStudent();
void GetPassRate();
void ShowInfo();
static int count; //使用静态变量更好
static int total;
static float rate;
private:
string id;
string name;
string teacher;
Student s[70]; //使用数组,能够灵活录入多个学生信息
};
int Lesson::count=0; //类外初始化变量
int Lesson::total=0;
float Lesson::rate=-1;
void Student::display()
{
cout<<"id:"<<num<<endl<<"name:"<<name<<endl<<"score:"<<score<<endl;
}
void Lesson::AddStudent()
{
int x;
string num;
string name;
float score;
for(int i=0;i<70;i++)
{
cout<<"Please input student"<<i+1<<"'s id,name and score:"<<endl;
cin>>num>>name>>score;
s[i]=Student(num,name,score);
if(score>=60)
count++;
total++;
cout<<"input 0 to exit,or any other number to continue:";//退出录入功能
cin>>x;
if(x==0)
break;
}
}
void Lesson::GetPassRate()
{
rate=(float)count/total;
}
void Lesson::ShowInfo()
{
int k=0;
cout<<"Lesson's id:"<<id<<endl<<"Name:"<<name<<endl<<"Teacher:"<<teacher<<endl;
cout<<"The pass rate is "<<rate<<endl;
for(;k<total;k++)
s[k].display();
}
int main()
{
Lesson L1("01","Math","Li");
L1.AddStudent();
L1.GetPassRate();
L1.ShowInfo();
return 0;
}