2016-06-13 85 views
-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; 
    } 
} 

我希望有人能帮助我了:)

+1

我不清楚你在问什么。 – Ian

+5

你不清楚你的意思是“这是必须改变数组的代码,但它不是做'我们需要一个简短的自包含的例子和一个特定的问题描述,如果我们要帮助你。看看这个:https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –

+0

*是的,我知道名称空间的使用不是一个好主意*,你确定吗?你是不是指*使用指令*是个坏主意? – PcAF

回答

1

你在两个回合中都有players._symbolPlayer1

+0

这是一个非常值得的评论 - 绝对需要指出 - 但不是一个好的答案。你非常接近评论专家所需的50人,这很重要,所以我不想倒下,但是我也不能证明你是否满意。 – user4581301