我刚刚上课,但是我收到了这个错误,这让我感到空白。我查看了其他帖子,但不知道我的代码有什么问题?我已经对代码进行了评论。
class myClass { //Class which might cause an issue? Don't see whats wrong with it.
public:
myClass(string nm) {
setName(nm);
}
void setName(string x) {
name = x;
}
string getName() {
return name;
}
private:
string name;
};
int main() {
cout << "Task 1, Task 2, Task 3, Task 4 ?" << endl;
int answer;
cin >> answer;
switch (answer)
{
case 1://Practising Classes
CRectangle area;
cout << "Enter two numbers \n";
cin >> area.x;
cin >> area.y;
cout << "Area is: "<< area.findArea() << endl;
break;
case 2://Practising Classes
AddNumbers myObj1;
myObj1.getNumbers();
cout << myObj1.addNumbers() << endl;
case 3: //Practising Classes
birthdays b1;
cout << "Welcome to Birthdays! \n";
bool bool1 = false;
do {
cout << "Do you want to enter some data (1) or retrieve some? \n";
int answer;
cin >> answer;
switch (answer)
{
case 1:
b1.setdata();
break;
case 2:
b1.getdata();
}
} while (bool1 == false);
case 4: // This causes the error. // Testing out Constructors
myClass object("David");
myClass object2("Amy");
cout << object.getName();
}
system("PAUSE");
}
答案 0 :(得分:1)
这些case
“语句”实际上是标签,例如goto
。他们没有开始新的范围。当找到条件时,执行“跳转”到相关的案例标签并从那里继续。
The language's rules insist that you cannot "jump" over initialisations,因为以一致和可预测的方式允许这一点需要更复杂的标准措辞。
将你的案例置于他们自己的范围内,以“隔离”声明并防止它们“泄漏”到下一个案例中,这是编译器所关心的。
例如:
case 1: { //Practising Classes
CRectangle area;
cout << "Enter two numbers \n";
cin >> area.x;
cin >> area.y;
cout << "Area is: "<< area.findArea() << endl;
break;
}
我添加了{
和}
。这些不是switch
/ case
语法的一部分,而只是独立的范围块,就像这里的内部块一样:
int main()
{
int x = 42;
{
int x = 999; // a different x!
}
}