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

Accessing variables of a template from another class

本文关键字:变量 访问 另一个      更新时间:2023-10-16

我试图编写的一个小游戏程序有问题。我创建了一个模板类"Board",它包含一个类型为"T"的2D阵列,这样我就可以将该板用于不同类型的游戏。问题是在游戏中需要修改阵列(T板[SIZE][SIZE])。另一个类"Othello"有一个类型为"Tile"的"Board",它是一个包含两个变量的结构,"Player"(由另一个类别定义)用于说明哪个玩家控制着Tile,以及两个布尔变量"black"answers"white"用于说明任何一个玩家是否可以移动到那里。所以这基本上就是它的样子:

板:

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

问题是,我不能直接通过"Othello"类修改"Board"(我不能通过Othello类访问该板,所以othelloBoard[x][y].current=WHITE;例如,不起作用),但我不能在"Board"中定义修饰符函数,因为类型可以是任何类型。我似乎不知道该怎么做。也许我错过了一些非常简单的东西。这不是一个学校项目,我正在重温我第一门C++课程中的一个旧项目,并试图自己重建它。谢谢你的帮助!

问题是:什么是董事会?它提供了什么抽象(如果有的话)?你没有在这里显示类函数,所以我现在真的没有。当你试图使用它时,它似乎毫无用处。无论如何,使用一个非常浅的封装,您可以只为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游戏就可以实例化另一个版本的模板来改变大小)