C++ 菜单代码 - 运行另一个类

C++ Menu Code - Running another Class

本文关键字:另一个 运行 菜单 代码 C++      更新时间:2023-10-16

好的,所以我即将完成我在这个简单C++游戏上的工作,现在只需将类连接在一起,可以这么说,这样当某个事件发生时,它将开始从另一个类运行代码。

然而,我的菜单是一个特别顽固的问题。我试图设置它,以便当用户输入选项"1"作为他们的选择时,它开始在另一个C++文件中运行地图代码,但它没有。

每当我尝试运行代码时,它都会给我以下 3 个错误。

1   IntelliSense: transfer of control bypasses initialization of:
        variable "A" (declared at line 37)  e:C++ - CopyMenu_3Menu_3Menu.cpp    27  3   Menu_3
2   IntelliSense: class "Map" has no member "standby"   e:C++ - CopyMenu_3Menu_3Menu.cpp    38  6   Menu_3
3   IntelliSense: return value type does not match the function type    e:C++ - CopyMenu_3Menu_3Menu.cpp    46  9   Menu_3

这是我的菜单代码:

#pragma once
#include "Map.h"
#include "Menu.h"
#include <iostream>
#include <string>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::string;
Menu::Menu()
{
}
void menu()
{
    int choice;
    bool gameOn = true;
    while (gameOn != false){
        cout << " 1 - Playn";
        cout << " 2 - Quitn";
        cin >> choice;
        switch (choice)
        {
        case 1:
            cout << "Your adventure starts now!n";
            system("PAUSE");
            cout << "Welcome to ATAG brave adventurer!n";
            system("PAUSE");
            //Starts the next part of the game, in this case, the map
            Map A;
            A.standby();
        //Ends the game
        case 2:
            system("PAUSE");
            exit(0);
        }
    }
    return 0;
}
Menu::~Menu()
{
}

仅供参考,我正在使用Visual Studio 2013,以防有帮助。任何人都得到了任何建议,因为就代码而言,这可能是阻止我完成项目的最后一件事,如果有人能告诉我如何使这 3 个错误消失,我将不胜感激。

这是一个很好的解释,为什么你会遇到这个问题 -> 为什么不能在 switch 语句中声明变量?

如何修复 - 只需将case身体包裹在大括号中即可。这将变量A的范围限制为那些大括号(不是整个switch(。

case 1: {
    cout << "Your adventure starts now!n";
    system("PAUSE");
    cout << "Welcome to ATAG brave adventurer!n";
    system("PAUSE");
    Map A;
    A.standby();
} break;
相关文章: