从另一个类访问模板的变量
Accessing variables of a template from another class
我试图编写的一个小游戏程序有问题。我创建了一个模板类"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游戏就可以实例化另一个版本的模板来改变大小)
相关文章:
- 从不同C++类的成员变量访问成员函数
- 在主函数中C++私有变量访问
- 互锁变量访问(在布尔值上)和 std::atomic_flag 之间的区别
- C++中的变量访问内联函数
- 无法使用子类变量访问超类公共成员
- 优化成员变量访问
- Ifstream:打开可使用变量访问的文件
- 使用'this->'成员变量访问的性能
- 从成员变量访问静态 constexpr 成员,GCC 错误?
- TLS变量访问的结果未缓存
- 通过const成员变量访问内联函数
- 获取通过环境变量访问的文件的位置
- 静态变量访问
- 从函数变量访问结构变量的成员
- 从另一个变量访问变量
- 使用变量访问结构中的任何数据
- 如何使用另一个变量访问对象的变量/方法
- 使用用户变量访问结构的成员?C++
- 我需要通过基类静态变量访问派生类成员
- 如何将一个文件中存在的全局常量变量访问到另一个文件