为什么我的编译器抱怨这不是 class 或名称空间?

Why is my compiler complaining that this isn't a class or namespace?

我正在尝试用 QT 编写一个扫雷游戏,但我在每一步都被阻止了。目前 QT Creator 抱怨以下代码:

> #include <QApplication>
  #include "mainwindow.h"
  #include "sweepermodel.h"
  #include <iostream>
  #include <QTime>
  #include <string>

  int main(int argc, char *argv[])
  {
      QApplication a(argc, argv);
      SweeperModel *sweeperModel = new SweeperModel(16, 16, 40);
      sweeperModel->gameState = SweeperModel::GAME_STATE::Playing;
      MainWindow w;
      w.show();

      return a.exec();
  }

它指出:

"C:\Users\nthexwn\Workspace\AISweeper\main.cpp:12: error: 'SweeperModel::GAME_STATE' is not a class or namespace"

回到 SweeperModel 头文件,我们可以看到 GAME_STATE 确实是在那里声明的枚举:

#ifndef SWEEPERMODEL
#define SWEEPERMODEL

#include <vector>
#include "sweepernode.h"

// Abstraction of the game grid as a 1-dimensional vector along with a flag
// indicating game state.
class SweeperModel
{
public:

// Possible game states from a player's perspective.
enum GAME_STATE
{
    Loading,
    Error_Height,
    Error_Width,
    Error_Mines,
    Playing,
    Lost,
    Won,
    Exiting,
};

GAME_STATE gameState;
short height;
short width;
short mines;

int getRandomValue(int low, int high);
void assignMinesToModel(SweeperModel *sweeperModel);
SweeperModel(short height, short width, short mines);
~SweeperModel();
SweeperNode& getNode(short row, short column);

private:
    std::vector<SweeperNode*> nodes;
};

#endif // SWEEPERMODEL

我在这里忘记了什么?我怎样才能使这项工作?

首先,enum 不会创建名称空间,因此您的代码应该是

sweeperModel->gameState = SweeperModel::Playing;

其次,c++11推荐枚举class,喜欢

enum class enum_name{ firstone, secondone, thirdone};

如果在"enum"后面加上关键字"class",效果也很好。 最后,MSVC 会自动将枚举视为具有命名空间,因此您的代码在 MSVC 中也能正常工作;