创建一个学生类,该类有姓名、学号、语文成绩数据成员。构造函数初始化每一个数据成员,成员函数changeValue是改变该学生的语文成绩,然后利用display将数据输出出来。 程序要求: (1)对构造函数进行重载 (2)建立作用域不同的类对象,查看其析构函数的析构顺序
时间: 2024-02-12 19:09:34 浏览: 21
好的,以下是对应的代码:
```c++
#include <iostream>
#include <string>
class Student {
private:
std::string name; // 姓名
int id; // 学号
int chineseScore; // 语文成绩
public:
// 构造函数重载
Student(): name(""), id(0), chineseScore(0) {}
Student(std::string name, int id, int chineseScore): name(name), id(id), chineseScore(chineseScore) {}
// 成员函数
void changeValue(int score) {
chineseScore = score;
}
void display() {
std::cout << "姓名:" << name << std::endl;
std::cout << "学号:" << id << std::endl;
std::cout << "语文成绩:" << chineseScore << std::endl;
}
// 析构函数
~Student() {
std::cout << "调用了析构函数" << std::endl;
}
};
int main() {
// 创建对象1
{
Student stu1("张三", 1001, 90);
stu1.display();
stu1.changeValue(95);
stu1.display();
}
std::cout << "-----分割线-----" << std::endl;
// 创建对象2
{
Student stu2("李四", 1002, 85);
stu2.display();
stu2.changeValue(92);
stu2.display();
}
return 0;
}
```
程序输出:
```
姓名:张三
学号:1001
语文成绩:90
姓名:张三
学号:1001
语文成绩:95
调用了析构函数
-----分割线-----
姓名:李四
学号:1002
语文成绩:85
姓名:李四
学号:1002
语文成绩:92
调用了析构函数
```
可以看到,先创建的对象先被销毁,所以析构函数的析构顺序是先析构对象1,再析构对象2。