-1
當我想要從另一個類的類中更改數組的值時,它實際上不會更改該數組的值。像數組[0] [0] ='X'不會工作。因此,這裏是代碼:C++從另一個類的類中更改數組
#pragma once
#include <iostream>
#include "players.h"
using namespace std;
class checkerBoard
{
public:
checkerBoard();
void initBoard();
void printBoard();
char Board[5][5];
private:
int boardheight = 5;
int boardwidth = 5;
char normalSymbol = '.';
players player;
};
棋盤類:
#include "checkerBoard.h"
checkerBoard::checkerBoard()
{
}
void checkerBoard::initBoard() {
for (int y = 0; y < boardheight; y++) {
for (int x = 0; x < boardwidth; x++) {
Board[y][x] = normalSymbol;
}
}
}
void checkerBoard::printBoard() {
for (int y = 0; y < boardheight; y++) {
for (int x = 0; x < boardwidth; x++) {
cout << Board[y][x];
cout << " ";
}
cout << endl;
}
}
是的,我知道使用命名空間的心不是一個好主意。 這是必須改變數組的代碼,但它沒有這樣做:
頁眉:
#pragma once
#include <iostream>
#include <string>
#include "players.h"
#include "checkerBoard.h"
using namespace std;
class tictactoeEngine
{
public:
tictactoeEngine();
void turnPlayer1();
void turnPlayer2();
int turn = 1;
players players;
checkerBoard board;
bool finished = false;
private:
int yCoordinates;
int xCoordinates;
};
CPP文件:
#include "tictactoeEngine.h"
tictactoeEngine::tictactoeEngine()
{
}
void tictactoeEngine::turnPlayer1() {
while (turn == 1) {
cout << "Wich Y-Coordinates are you using " << flush << players._namePlayer1 << " ?:";
cin >> yCoordinates;
cout << "And wich X-Coordinates are you using?: " << flush;
cin >> xCoordinates;
board.Board[yCoordinates + 1][xCoordinates + 1] = players._symbolPlayer1;
yCoordinates = 0;
xCoordinates = 0;
turn = 2;
}
}
void tictactoeEngine::turnPlayer2() {
while (turn == 2) {
cout << "Wich Y-Coordinates are you using " << flush << players._namePlayer2 << " ?:";
cin >> yCoordinates;
cout << "And wich X-Coordinates are you using?: " << flush;
cin >> xCoordinates;
board.Board[yCoordinates - 1][xCoordinates - 1] = players._symbolPlayer1;
yCoordinates = 0;
xCoordinates = 0,
turn = 1;
}
}
我希望有人能幫助我了:)
我不清楚你在問什麼。 – Ian
你不清楚你的意思是「這是必須改變數組的代碼,但它不是做'我們需要一個簡短的自包含的例子和一個特定的問題描述,如果我們要幫助你。看看這個:https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –
*是的,我知道名稱空間的使用不是一個好主意*,你確定嗎?你是不是指*使用指令*是個壞主意? – PcAF