Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何显示类中某个对象的枚举值?_C++_Class_Enums - Fatal编程技术网

C++ 如何显示类中某个对象的枚举值?

C++ 如何显示类中某个对象的枚举值?,c++,class,enums,C++,Class,Enums,我目前正在制作一个糟糕版本的游戏“战舰”,必须使用一个枚举数组来显示棋盘。我已经为我的标题创建了: enum class PlayerPiece { AIRCRAFT, BATTLESHIP, CRUISER, SUBMARINE, PATROL, EMPTY, }; class Board { public: PlayerPiece playerBoard[100]; PlayerPiece enemyBoard[100]; void re

我目前正在制作一个糟糕版本的游戏“战舰”,必须使用一个枚举数组来显示棋盘。我已经为我的标题创建了:

enum class PlayerPiece {
  AIRCRAFT,
  BATTLESHIP,
  CRUISER,
  SUBMARINE,
  PATROL,
  EMPTY,
 };

 class Board {
 public:

   PlayerPiece playerBoard[100];
   PlayerPiece enemyBoard[100];

   void reset();
   void display() const;

 };

当我找到我的源代码时,我试着将电路板显示为数字。到目前为止,在我运行重置命令后,电路板是空的。但是在我想要显示数组之后,我得到一个错误,它说“no operator如果您想查看与作用域枚举类型相关联的数字,请使用一个
静态\u cast
,如下所示:

cout << static_cast<int>(playerBoard[i]) << endl;

cout如果删除类并使用非作用域枚举编写枚举

enum PlayerPiece {

  AIRCRAFT,

  BATTLESHIP,

  CRUISER,

  SUBMARINE,

  PATROL,

  EMPTY,

 };
你可以打印你想要的号码

作用域和非作用域之间的区别(来自cplusplus.com):

在C++11之前,所有枚举基本上都是整数。您可以这样使用它们。这使得为需要一组受限值的函数提供坏值变得太容易了。例如:

1
2
3
4
5
6
7
8
9
10
enum round_mode { round_half_up, round_half_down, round_bankers };

double round( double x, round_mode = round_half_up )
{
   ...
};

    int main()
    {
      double x = round( 2.5, 42 );
}
编辑并运行

它可以编译,但并不漂亮

有了C++11,编译器现在知道了有关枚举的所有内容,并且不允许您随意地将它们与不正确的值混合在一起

本质上,它将枚举提升为一级对象——它不仅仅是一个整数

另一个问题是,每个枚举的名称都会流入包含范围。因此,以下情况可能会导致名称冲突:

一, 2. 枚举颜色_掩码{红色=0xFF0000,绿色=0x00FF00,蓝色=0x0000FF}; int red=0xFF0000

标识符“red”不能同时作为枚举值和整数变量名位于同一范围内

虽然这里的例子是人为设计的,但它离经常发生的事情并不遥远——程序员必须尽力避免

(一些标识符名称很常见。例如,“max”。如果您#include,则其中有一个“max”宏,如果您还#include并尝试使用“max”函数,或#include并尝试查找数字限制::max(),则会造成严重破坏。我知道这是一个宏问题,但这是我可能遇到的名字冲突…)

1
2
3
4
5
6
7
8
9
10
enum round_mode { round_half_up, round_half_down, round_bankers };

double round( double x, round_mode = round_half_up )
{
   ...
};

    int main()
    {
      double x = round( 2.5, 42 );
}