真心求c++编程,定义一个学生类Student,包括3个数据成员:学号id,姓名name

2024-12-05 01:42:06
推荐回答(2个)
回答1:

#include 
#include 
using namespace std;

class Student
{

public:
 // 带参数的构造函数初始化对象
 Student(int id, string name, double score) 
  : id(id), name(name), score(score)
 {
  count++;
  total+=score;
 }
 // 修改分数成员函数
 void ChangeScore(double newScore)
 {
  total +=newScore-score;

  score=newScore;
 }
 static double GetAverage()
 {
  return total / count;
 }
private:
 int id;
 string name;
 double score;
private:
 static double total;
 static int count;
};

// 类外对静态数据成员进行定义声明
double Student::total = 0.0f;
int Student::count= 0;

void main()
{
 // 声明四个学生对象并初始化
 Student s1(1001,"James", 86);
 Student s2(1001,"Kate", 67);
 Student s3(1001,"Lucy", 91);
 Student s4(1001,"LiLei", 65);
 
 cout<<"The average score is "<
 // 修改成绩
 s1.ChangeScore(50);
 s2.ChangeScore(50);
 s3.ChangeScore(50);
 s4.ChangeScore(50);

 cout<<"The average score is "<
system("pause");
}

回答2:

你好,看过你的需求,一下是一个示例代码,请参考:(已发送至你的邮箱)

// Copyright @ quark
// Date: 2010-10-22
#include
#include
using namespace std;

class Student
{

public:
// 带参数的构造函数初始化对象
Student(int id, string name, double score)
: id(id), name(name), score(score)
{
count++;
total+=score;
}
// 修改分数成员函数
void ChangeScore(double newScore)
{
total +=newScore-score;

score=newScore;
}
static double GetAverage()
{
return total / count;
}
private:
int id;
string name;
double score;
private:
static double total;
static int count;
};

// 类外对静态数据成员进行定义声明
double Student::total = 0.0f;
int Student::count= 0;

void main()
{
// 声明四个学生对象并初始化
Student s1(1001,"James", 86);
Student s2(1001,"Kate", 67);
Student s3(1001,"Lucy", 91);
Student s4(1001,"LiLei", 65);

cout<<"The average score is "<
// 修改成绩
s1.ChangeScore(50);
s2.ChangeScore(50);
s3.ChangeScore(50);
s4.ChangeScore(50);

cout<<"The average score is "<
system("pause");
}