定义一个描述学生基本情况的类Student,数据成员包括姓名、学号、英语成绩和高数成绩;成员函数包括构造函数、析构函数、获取姓名、获取学号、求出平均成绩,以及显示各科成绩和平均成绩的显示函数。编写main函数进行测试。
Student.h#include
#include
using namespace std;
class Student {
private:
char name[18];//姓名
int num;//学号
int mathScore, englishScore;//高数成绩,英语成绩
static int count, mathTotalScore, englishTotalScore;//人数,数学总,英语总
public:
Student(const char* nm, int nu, int math, int english) :num(nu), mathScore(math), englishScore(english)
{
strcpy(name, nm);//复制字符串
count++;
mathTotalScore += math;//数学总
englishTotalScore += english;//英语总
}//析构函数,释放字符数组
~Student() {
delete[]name;
}//显示基本数据:
void showBase();//显示静态数据:
static void ShowStatic() {
cout << "总人数:" << count << endl;
cout << "数学总成绩:" << mathTotalScore << endl;
cout << "英语总成绩:" << englishTotalScore << endl;
}
};
Student.cpp
#include
#include"Student.h"
using namespace std;
//静态成员数据初始化
int Student::count = 0;
int Student::mathTotalScore = 0;
int Student::englishTotalScore = 0;
void Student::showBase() {
cout << "显示基本数据:\n" << endl;
cout << "姓名:" << name << endl;
cout << "学号:" << num << endl;
cout << "数学成绩:" << mathScore << endl;
cout << "英语成绩:" << englishScore << endl << endl;
cout << "平均成绩:" << (mathScore+englishScore)/2<< endl;
}
main.cpp
#include
#include
#include "Student.h"
using namespace std;
int main() {
//对象数组
Student stu[3] =
{
Student("ww",2018,78,76),
Student("yy",2019,88,86),
Student("xx",2020,90,96)
};//遍历输出数组,打印基本数据
for (int i = 0; i < 3; i++)
{
stu[i].showBase();
}
//打印静态数据
stu->ShowStatic();
system("pause");
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)