#include <iostream> using namespace std; class MyClass { public: // ERROR ********found******** 请勿更改参数名 MyClass(int x) :flag(x) {}//构造函数不具有返回值,故删除 void Judge(); private: int flag; }; // ERROR ********found******** void Judge() { switch (flag) { case 0: cout << "False" << endl; // ERROR ********found******** break; default: cout << "True" << endl; break; } } int main() { MyClass obj(0); obj.Judge(); return 0; }
时间: 2023-07-19 16:48:27 浏览: 51
这段代码存在两个错误。
第一个错误是在 `MyClass` 类的构造函数中,构造函数不具有返回值,故需要将函数头中的 `int` 类型的返回值删除,正确的构造函数应该是:
```c++
MyClass(int x) :flag(x) {}
```
第二个错误是在 `MyClass` 类的 `Judge()` 函数中,访问了类的私有成员变量 `flag`,但是该函数并不是类的成员函数,因此需要将该函数修改为类的成员函数,并在函数头中添加类名和作用域解析符 `::`,正确的函数定义应该是:
```c++
void MyClass::Judge() {
switch (flag)
{
case 0:
cout << "False" << endl;
break;
default:
cout << "True" << endl;
break;
}
}
```
修改后的代码如下:
```c++
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass(int x) :flag(x) {}
void Judge();
private:
int flag;
};
void MyClass::Judge() {
switch (flag)
{
case 0:
cout << "False" << endl;
break;
default:
cout << "True" << endl;
break;
}
}
int main() {
MyClass obj(0);
obj.Judge();
return 0;
}
```
运行结果为:
```
False
```