gpt4 book ai didi

c++ - 如何制作board1 [{1,1}] ='X';大学工作

转载 作者:行者123 更新时间:2023-12-02 10:08:02 25 4
gpt4 key购买 nike

我需要使这一行在我的主要功能board1[{1,1}]='X';中工作。
我不知道如何使它工作。我想得到一些帮助。
这是我的董事会类(class):

class Board {
private:
int size;
char** matrix = nullptr;

public:

Board(int sizeToSet) { //constructor with size
size = sizeToSet;

matrix = new char*[size]; //creates a matrix
for (int i = 0; i < size; i++)
matrix[i] = new char[size];

for (int i = 0; i < size; i++) { //makes every cell in matix '.'
for (int j = 0; j < size; j++) {
matrix[i][j] = '.';
}
}
}

void printSize() { //matrix size print
cout << size << endl;
}

~Board() { //destructor
for (int i = 0; i < size; i++)
delete[] matrix[i];
delete[] matrix;
}

Board(const Board& other) { //copy constructor
size = other.size;
matrix = new char*[size];

for (int i = 0; i < size; i++)
matrix[i] = new char[size];

for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = other.matrix[i][j];
}
}
}

friend ostream& operator<<(ostream& os, const Board& boardToPrint) { //prints matrix
for (int i = 0; i < boardToPrint.size; i++) {
for (int j = 0; j < boardToPrint.size; j++) {
os << boardToPrint.matrix[i][j] << " ";
}
os << endl;
}
return os;
}
int operator()(int row, int col) {
cout << "it worked1" << endl;
return 1;

}
};

最佳答案

您想要做的是用对或类似的对operator[]重载

char & operator[]( const std::pair<size_t, size_t> &pair ) {
return matrix[pair.first][pair.second]
}

然后您可以通过执行以下操作来调用此函数
Board board1{10};
// …
board1[{0,0}] = 'X';

由于 std::pair可以通过 {x,y}初始化,其中 xy是数字。

关于c++ - 如何制作board1 [{1,1}] ='X';大学工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com