Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - How to access a private variable that is a 2D array with getter function

Im making a chess game and I have a board class that looks something like this:

class Board {
private:
    Tile tiles[8][8];
public:
    Tile getTiles() {
        return **tiles;
    }
}

where Tile is another class with its member that I want to access.

The problem is that I cant really do something like:

void foo() {
    Board board;
    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            board.getTiles()[i][j].getPosition(); //visibly makes no sense and gives an error
        }
    }
}

How should I access this array and is it even possible?

question from:https://stackoverflow.com/questions/65891444/how-to-access-a-private-variable-that-is-a-2d-array-with-getter-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, a Board is a collection of tiles. From a high level perspective, that's all it does. That it's stored as a 1D array, a 2D array, an hash map or a self balancing binary tree does not matter for the user. All that matters is that there are tiles in it.

So, you should instead do it that way:

Tile getTile(int row, int column) const {
    return tiles[row][column];
}

Alternatively, return by reference to avoid a copy and/or allow external modifications, but don't forget about const correctness:

const Tile& getTile(int row, int column) const;
Tile& getTile(int row, int column);

Then, if you change your mind and decide to go for a one dimentional array, well, it's easy!

Tile getTile(int row, int column) const {
    return tiles[row * 8 + column];
}

The external API does not change, no user code breaks, and everyone can go on with their lives.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...