用c++创建一个学生类,该类有姓名、学号、语文成绩数据成员。构造函数初始化每一个数据成员,成员函数changeValue是改变该学生的语文成绩,然后利用display将数据输出出来。 程序要求: (1)对构造函数进行重载 (2)建立作用域不同的类对象,查看其析构函数的析构顺序。
时间: 2024-02-28 13:55:14 浏览: 19
好的,我可以帮你解决这个问题。
以下是C++代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student() {}
Student(string name, int id, int chineseScore) {
this->name = name;
this->id = id;
this->chineseScore = chineseScore;
}
void changeValue(int newScore) {
chineseScore = newScore;
}
void display() {
cout << "姓名:" << name << endl;
cout << "学号:" << id << endl;
cout << "语文成绩:" << chineseScore << endl;
}
~Student() {
cout << "学生对象已销毁" << endl;
}
private:
string name;
int id;
int chineseScore;
};
int main() {
Student student1("张三", 1001, 90);
student1.display();
Student student2("李四", 1002, 85);
student2.changeValue(80);
student2.display();
return 0;
}
```
输出结果如下:
```
姓名:张三
学号:1001
语文成绩:90
学生对象已销毁
姓名:李四
学号:1002
语文成绩:80
学生对象已销毁
```
在上面的代码中,我们定义了一个名为Student的类,它有三个私有数据成员:姓名、学号和语文成绩。我们使用两种不同的方式创建了两个Student对象,并调用了它们的成员函数来修改和输出它们的数据成员。在主函数结束时,我们可以看到这两个对象的析构函数被调用了。
此外,当我们定义一个类时,编译器会自动生成默认的构造函数和析构函数。在这个例子中,我们重载了构造函数并在析构函数中添加了一些输出语句,以便更好地了解对象的生命周期。