枚举类别范围-C

Enum class out of scope - C++

本文关键字:范围 枚举      更新时间:2023-10-16

这是我当前的程序标题文件

#ifndef BOARD_H
#define BOARD_H
class Board {
enum class EnemyPiece {HIT, MISS, EMPTY};
enum class PlayerPiece {AIRCRAFT, BATTLESHIP, CRUISER, SUBMARINE, PATROL, EMPTY};
  private:
     PlayerPiece playerboard[100];
     PlayerPiece enemyboard[100];
  public:
     Board();
     void reset(PlayerPiece *a , PlayerPiece *b);
   };
#endif

这是CPP文件

#include <iostream>
#include "Board.h"
using namespace std;
 Board::Board()
 {
  reset(playerboard, enemyboard);
 }
 void Board::reset(PlayerPiece *year, PlayerPiece *month)
 {
  std::cout << static_cast<std::underlying_type<PlayerPiece>::type>(PATROL) << std::endl;
 }

在成员功能中,我试图施放枚举类型在此范围内未宣布"巡逻"我做错了什么吗?应该把枚举类放在其他地方吗?

使用 enum class时,令牌将在类型下范围范围。因此,您需要使用PlayerPiece::PATROL而不是PATROL

来自C 11标准:

7.2枚举声明

...

2 ... enum-keys enum classenum struct在语义上是等效的;其中一种声明的枚举类型是A scoped Eneumeration ,其枚举 scopeped枚举者。。

尝试

Board::PlayerPiece::PATROL

Just

PlayerPiece::PATROL

因为枚举是在类范围内使用的。

,如果您要接受公共成员功能的参数,则声明公众等枚举。

似乎有一个错字

#ifndef BOARD_H
#define BOARD_H
#ifndef BOARD_H
^^^^^^^^^^^^^^^

删除最后的#ifndef