PTAC++CPP-25-类和对象答案
时间: 2025-07-06 12:47:34 浏览: 5
### C++ 类和对象练习题解答
#### 题目描述
创建一个名为 `Student` 的类来表示学生的信息。该类应包含学生的姓名、年龄以及成绩三个私有成员变量。提供公有的设置函数(setters)和获取函数(getters),用于访问这些属性。此外,还需实现一个计算平均分的方法。
#### 解决方案
定义如下所示的 `Student` 类:
```cpp
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
double score;
public:
// 构造函数初始化列表
Student(std::string n = "", int a = 0, double s = 0.0):name(n), age(a), score(s){}
// 设置器方法
void setName(const std::string& newName) { this->name = newName; }
void setAge(int newAge) { this->age = newAge; }
void setScore(double newScore) { this->score = newScore; }
// 获取器方法
const std::string& getName() const { return this->name; }
int getAge() const { return this->age; }
double getScore() const { return this->score; }
// 计算并返回平均分数
static double calculateAverage(Student students[], int size){
if (size <= 0) return 0.0;
double sum = 0.0;
for (int i = 0; i < size; ++i) {
sum += students[i].getScore();
}
return sum / size;
}
};
```
此代码片段展示了如何声明带有私有数据成员的类,并提供了公共接口以便外部程序可以安全地操作这些数据[^1]。
为了测试上述类的功能,下面是一个简单的主函数例子:
```cpp
int main(){
// 创建两个 student 对象实例化
Student stu1("Alice", 20, 95);
Student stu2("Bob", 22, 87);
// 打印信息前修改 Bob 的成绩
stu2.setScore(92);
// 输出 Alice 和 Bob 的名字与成绩
std::cout << "Name: " << stu1.getName()
<< ", Score: " << stu1.getScore() << '\n';
std::cout << "Name: " << stu2.getName()
<< ", Score: " << stu2.getScore() << '\n';
// 使用静态方法计算两人平均分
Student list[] = {stu1, stu2};
std::cout << "The average score is "
<< Student::calculateAverage(list, sizeof(list)/sizeof(*list))
<< "\n";
return 0;
}
```
这段代码通过具体的应用场景说明了怎样利用之前定义好的 `Student` 类来进行实际编程工作[^2]。
阅读全文
相关推荐


















