我正在开发一个清单系统,以应对目前我所知道的C ++数量的挑战,我正在使用带有枚举索引的数组,并使用值true或false进行初始化。这是代码:

using namespace std;

enum items
{
    LASER_RIFLE,
    LASER_SWORD,
    LASER_PISTOL,
    PLASMA_LAUNCHER,
    MAX_ITEMS
};


void playerInventory()
{
    bool items[MAX_ITEMS];
    items[LASER_RIFLE] = true;
    items[LASER_SWORD] = false;
    items[LASER_PISTOL] = false;
    items[PLASMA_LAUNCHER] = true;

    int itemName;
    for (int item = 0; item <= MAX_ITEMS; ++item)
        if (items[item] == true)
        {
            switch (itemName)
            {
            case 1:
                cout << "Laser Rifle\n";
                break;
            case 2:
                cout << "Laser Sword\n";
                break;
            case 3:
                cout << "Laser Pistol\n";
                break;
            case 4:
                cout << "Plasma Launcher \n";
                break;
            }
        }
        else
            cout << "Not in Inventory\n";
}


该语句仅对激光手枪评估为真,对其他所有评估为假。我不知道为什么会这样。

最佳答案

您正在切换itemName。您应该切换为item
默认情况下的枚举从0开始,而不是1。您的案例应从0开始。
在for循环中,您必须检查<而不是<=


结果如下:

#include <iostream>
using namespace std;

enum items
{
    LASER_RIFLE,
    LASER_SWORD,
    LASER_PISTOL,
    PLASMA_LAUNCHER,
    MAX_ITEMS
};


void playerInventory()
{
    bool items[MAX_ITEMS];
    items[LASER_RIFLE] = true;
    items[LASER_SWORD] = false;
    items[LASER_PISTOL] = false;
    items[PLASMA_LAUNCHER] = true;

    int itemName;
    for (int item = 0; item < MAX_ITEMS; ++item) {
        if (items[item] == true)
        {
            switch (item)
            {
            case 0:
                cout << "Laser Rifle\n";
                break;
            case 1:
                cout << "Laser Sword\n";
                break;
            case 2:
                cout << "Laser Pistol\n";
                break;
            case 3:
                cout << "Plasma Launcher \n";
                break;
            }
        }
        else {
            cout << "Not in Inventory\n";
        }
    }
}

int main() {
    playerInventory();
    return 0;
}


参见:ideone

09-17 19:51