设计学生类,包括学号、姓名、成绩,计算学生的平均成绩的成员函数以及构造函数和析构函数,c++
时间: 2023-06-12 20:04:38 浏览: 89
以下是设计学生类的示例代码:
```c
#include <iostream>
#include <cstring>
using namespace std;
class Student {
private:
char id[20];
char name[20];
int score;
public:
Student(char *id_, char *name_, int score_) {
strcpy(id, id_);
strcpy(name, name_);
score = score_;
}
~Student() {}
float avgScore() {
return score / 3.0;
}
};
int main() {
char id[] = "10001";
char name[] = "张三";
int score = 90;
Student stu(id, name, score);
cout << "学生平均成绩为:" << stu.avgScore() << endl;
return 0;
}
```
在上述代码中,我们定义了一个名为 `Student` 的类,它包含了私有成员变量 `id`、`name`、`score`,分别代表学号、姓名和成绩。该类还包含了一个构造函数,用于初始化这些成员变量,以及一个析构函数。为了计算平均成绩,我们还添加了一个 `avgScore` 函数,它返回学生的平均成绩(假设学生只有三门课程)。在 `main` 函数中,我们创建了一个 `Student` 类的对象 `stu`,并调用其 `avgScore` 方法计算平均成绩。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)