简体   繁体   English

C ++圆形结构

[英]C++ Circular Struct

Okay, so essentially I have a struct of a piece on a board, as follows: 好的,基本上,我在板上有一块结构,如下所示:

struct piece
{
    int value;
    bool revealed;
    bool canMove(int x, int y)
    {
        //This is where the problem is.
        if (board[x][y].value == 13) //If it's not occupied
            return true;
        else
            return false;
    }
};

//Define the board
piece board[x][y];

And it's giving me errors such as 'board': undeclared identifier . 这给了我错误,例如'board':未声明的identifier How can I fix this? 我怎样才能解决这个问题? I've tried putting the board declaration before the struct, but then it just says that piece is an undeclared identifier. 我试过将板声明放在该结构之前,但是它只是说那是一个未声明的标识符。

I realize I could just pass in the board as a parameter, but I have several functions, and that would take a lot more time than I would like, so if there is any other solution, please tell me! 我意识到我可以只将板子作为参数传递,但是我有几个功能,这将花费比我更多的时间,因此,如果有其他解决方案,请告诉我!

This question is related (but not identical) to Question 这个问题是有关(但不相同),以质询

You have to decouple the class definition from the implementation of its member functions, so that the compiler always knows what you're talking about: 您必须将类定义与其成员函数的实现分离开来,以便编译器始终知道您在说什么:

struct piece
{
    int value;
    bool revealed;
    bool canMove(int x, int y);  // this is sufficient for the moment
};

piece board[x][y];   // now, compiler knows what a piece is. 

bool piece::canMove(int x, int y) 
{                    // now board is known as well
    if (board[x][y].value == 13) 
        return true;
    else
        return false;
}

Declare canMove inside the class, then define it outside after you have declared board . 声明canMove在类内部,然后在声明board之后在外部定义它。 At that point you can successfully refer to board . 此时,您可以成功参考board

You are mixing piece with pieces. 您正在一块一块地混合。 This is really wrong design. 这确实是错误的设计。

Your method canMove belongs to single piece. 您的方法canMove属于单件。 So its definition should rdflect this fact: 因此,其定义应反映以下事实:

bool canMove() const
{
  return value == 13;
}

To get what you want to get from 2D array of pieces - just do: 要获得想要从2D数组阵列中获取的内容,请执行以下操作:

board[x][y].canMove()

Of course you can creare new class Board to encapsulate its behaviour,like methods canMove with 2 arguments. 当然,您可以创建新的类Board来封装其行为,例如方法canMove带有2个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM