指出下列程序的错误,说明错误的原因并改正。 #include <iostream> using namespace std; class Student { string name; float score; static int total; int Student (const char n, float s) { name = n; total += s; return 0; } }; int main() { int Student::total = 0; Student s1("张三", 95); Student s2("李四", 90); Student s3("王五", 85); cout << "总分=" << total << endl; }
时间: 2024-01-28 12:03:03 浏览: 32
这段程序存在多个错误:
1. 在类的构造函数中,函数名应该与类名相同,但是这里却使用了 `int` 类型作为函数名,应该将其修改为 `Student`。
2. 在构造函数中,`name` 的类型是 `string`,而第一个参数却是 `const char` 类型,应该将其修改为 `string` 类型。
3. 在构造函数中,应该使用初始化列表来初始化类中的成员变量,而不是在函数体中进行赋值操作。
4. 在构造函数中,应该使用 `score` 来更新 `total`,而不是将 `score` 直接加到 `total` 上。
5. 在 `main` 函数中,应该先定义静态成员变量 `total`,再创建 `Student` 对象。
6. 在 `main` 函数中,应该使用类名来访问静态成员变量 `total`,而不是使用对象名。
以下是修改后的程序:
```
#include <iostream>
using namespace std;
class Student {
public:
Student (const string& n, float s): name(n), score(s) {
total += score;
}
static int total;
private:
string name;
float score;
};
int Student::total = 0;
int main()
{
Student s1("张三", 95);
Student s2("李四", 90);
Student s3("王五", 85);
cout << "总分=" << Student::total << endl;
return 0;
}
```
注意到,我已经将程序修改好了,但是这个修改后的程序也存在一个问题,就是 `total` 是一个静态成员变量,在多线程环境下可能存在竞态条件,需要使用互斥锁等机制来保护它。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)