简体   繁体   中英

Accessing variables of a template from another class

I have an issue with a small game program I'm trying to write. I created a template class "Board" that holds a 2D array of type "T" so that I can use the board for different types of games. The issue is that the array (T board[SIZE][SIZE]) needs to be modified during the game. Another class "Othello" has a "Board" of type "Tile" which is a struct that contains two variables, "Player" (defined by another class) to state which player is in control of the tile, and two bool variables "black" and "white" to state if either player can move there. So this is basically what it looks like:

Board:

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

Othello:

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

The issue is that I can't modify the "Board" directly through the "Othello" class (I can't access the board through the Othello class, so othelloBoard.board[x][y].current = WHITE; for instance doesn't work), but I can't define a modifier function within "Board" since the type can be anything. I can't seem to wrap my head around how I would go about doing this. Maybe I'm missing something really simple. This isn't a school project, I'm revisiting an old project from my first C++ course and trying to rebuild it myself. Thanks for any help!

The question is: what is a Board? And what abstraction does it provide (if any)? You didn't show the class function here so I don't really now. As you seem to try to use it, it seems pretty useless. Anyway with a very shallow encapsulation, you can just provide accessors for 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]
};

(note that I moved the SIZE as a template parameters, so that your future Tic-Tac-Toe game can instantiate another version of the template changing the size)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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