此程序参考自《C++面向对象程序设计教程(第三版)》,陈维兴,林小茶编著,Page98。
此程序代码采用C++语言编写,通过设计一个score类来储存各科成绩(例子中为Math,Physics,Chinese),再通过设计student类来储存学生的姓名,学号,并通过类的组合方式求其个人成绩平均,班级每个人单科成绩平均分的总平均,同时还显示学生人数。
要点:
1.采用类的组合。
2.采用static设置静态变量,保持类的封装性。
代码:
/************************************************************************/
/* This procedure is written by Zhaolinux in Auguest.10th/2018 */
/************************************************************************/
#include <IOSTREAM.H>
#include <STRING.H>
//To define the the class of the score
class score
{
public:
score(float s1,float s2,float s3,int sub_num);
float return_total_score();
float return_sigle_ave_score();
void show_sigle_score();
private:
int subject_num;
float math;
float physics;
float chinese;
float Total_score;// new define
float sigle_ave;
};
score::score(float s1,float s2,float s3,int sub_num):math(s1),physics(s2),chinese(s3),subject_num(sub_num)
{
Total_score=s1+s2+s3;
sigle_ave=Total_score/sub_num;
}
float score::return_total_score()
{
return Total_score;
}
float score::return_sigle_ave_score()
{
return sigle_ave;
}
void score::show_sigle_score()
{
cout<<"Math Score:"<<math<<endl;
cout<<"Physics Score:"<<physics<<endl;
cout<<"Chinese Score:"<<chinese<<endl;
cout<<"The Total Score Is:"<<Total_score<<endl;
cout<<"The Sigle Average Score Is:"<<sigle_ave<<endl;
}
//--------------------------------------------------------------------------
class Student
{
public:
Student(char *name1,char *number1, float s1, float s2, float s3,int subject);
~Student();
void show();
void show_count_sum_ave();
private:
char *stu_name;
char *stu_number;
score score1;
static int count;
static float sum;
static float ave;
};
Student::Student(char *name1,char *number1,float s1, float s2, float s3,int subject):score1(s1,s2,s3,subject)
{
stu_name=new char[strlen(name1)+1];
strcpy(stu_name,name1);
stu_number=new char[strlen(number1)+1];
strcpy(stu_number,number1);
++count; //It is not a global variable, it is a static variable
//It will be initialized at the begining of calling just for one time
sum=sum+score1.return_sigle_ave_score();
ave=sum/count;
}
Student::~Student()
{
delete []stu_name;
delete []stu_number;
--count;
sum=sum-score1.return_total_score();
}
void Student::show()
{
cout<<"*********************************"<<endl;
cout<<"**STU_Name: "<<stu_name<<endl;
cout<<"**STU_Number:"<<stu_number<<endl;
cout<<"*********************************"<<endl;
cout<<" *STU_Score* "<<endl;
score1.show_sigle_score();
}
void Student::show_count_sum_ave()
{
cout<<"**Class_Ave:"<<ave<<endl;
cout<<"**Count_Stu:"<<count<<endl;
}
int Student::count=0;
float Student::sum=0.0;
float Student::ave=0.0;
int main()
{
Student stu1("Bai Juyi","192339",76,66,88,3);
Student stu2("Li Xiaohua","192334",98,89,92,3);
Student stu3("Wang Fenglang","192105",65,66,73,3);
stu1.show();
//stu1.show_count_sum_ave();
stu2.show();
stu3.show();
cout<<endl;
stu2.show_count_sum_ave();
return 0;
}