簡體   English   中英

從另一個類訪問模板的變量

[英]Accessing variables of a template from another class

我正在嘗試編寫一個小游戲程序的問題。 我創建了一個模板類“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
};

問題是我無法通過“奧賽羅”類直接修改“Board”(我無法通過Othello類訪問該板,所以othelloBoard.board [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游戲可以實例化更改大小的模板的另一個版本)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM