【问题标题】:Enum class out of scope - C++枚举类超出范围 - C++
【发布时间】:2017-04-21 18:05:10
【问题描述】:

这是我目前的程序 头文件

#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;
 }

在成员函数中,我尝试强制转换枚举类型,但是无论我将减速完成的头文件放在哪里,我都会不断得到 “PATROL”未在此范围内声明 有什么我做错了吗?枚举类是否应该放在其他地方?

【问题讨论】:

  • 使用PlayerPiece::PATROL。
  • 别再使用大写字母了,这种可怕的黑客攻击已经没有必要了。
  • #ifndef BOARD_H #define BOARD_H #ifndef BOARD_H ... 应该如何工作?你的枚举定义是私有的,怎么会有人调用reset 函数?
  • 为什么你有两倍的#ifndef BOARD_H?这是复制/粘贴错误还是真的存在于您的文件中?无论如何,您必须删除第二次出现..
  • 抱歉第二次出现,复制时打错了。

标签: c++ class enums scope


【解决方案1】:

当您使用enum class 时,标记的范围在类型之下。因此,您需要使用PlayerPiece::PATROL 而不仅仅是PATROL。

来自 C++11 标准:

7.2 枚举声明

...

2 ... enum-keys enum class 和 enum struct 在语义上是等价的;用其中之一声明的枚举类型是范围枚举,其枚举器是范围枚举器。

【讨论】:

    【解决方案2】:

    试试

    Board::PlayerPiece::PATROL
    

    只是

    PlayerPiece::PATROL
    

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

    如果您要接受它们作为公共成员函数的参数,则将枚举声明为 public。

    好像有错别字

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

    删除最后一个#ifndef

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多