从另一个类访问模板的变量

时间:2014-04-19 03:19:03

标签: c++ templates struct

我正在尝试编写一个小游戏程序的问题。我创建了一个模板类“Board”,它包含一个类型为“T”的2D数组,这样我就可以将该板用于不同类型的游戏。问题是在游戏过程中需要修改数组(T板[SIZE] [SIZE])。另一个类“Othello”有一个“Tile”类型的“Board”,它是一个包含两个变量的结构,“Player”(由另一个类定义)来说明哪个玩家控制了tile,以及两个bool变量“black如果任何一名球员都能在那里移动,那就说“和”白色“。所以这基本上就是它的样子:

板:

int SIZE = 8;
template<class T>
class Board {
public:
    // class functions
private:
    T board[SIZE][SIZE]
};

奥赛罗:

class Othello {
public:
    // class functions
private:
    // function helpers
struct Tile {
    Player current; // current tile holder (BLACK, WHITE, NEUTRAL)
    bool black; // can black capture?
    bool white; // can white capture?
    unsigned location; // number of the tile, counted from left to right
};

Board<Tile> othelloBoard; // board for the game

int bCounter; // counter for black units
int wCounter; // counter for white units

User playerOne; // information for first player
User playerTwo; // information for second player
};

问题是我无法通过“奥赛罗”课程直接修改“董事会”(我无法通过奥赛罗课程访问董事会,所以othelloBoard.board [x] [y] .current = WHITE ;例如不起作用),但我不能在“Board”中定义修饰符函数,因为类型可以是任何东西。我似乎无法理解我将如何做到这一点。也许我错过了一些非常简单的事情。这不是一个学校项目,我正在重新审视我的第一个C ++课程中的一个旧项目,并尝试自己重建它。谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

问题是:什么是董事会?它提供了什么抽象(如果有的话)?你没有在这里展示课堂功能,所以我现在不是。当你似乎试图使用它时,它似乎没用。无论如何,封装非常浅,您只需提供Tiles的访问器:

template<class T, int SIZE = 8>
class Board {
public:
    T &tileAt(int x, int y) {
        assert(x>=0 && x < SIZE && y>=0 && y<SIZE);
        return board(x, y);
    }

    // class functions

private:
    T board[SIZE][SIZE]
};

(请注意,我将SIZE作为模板参数移动,以便您未来的Tic-Tac-Toe游戏可以实例化更改大小的模板的另一个版本)