c ++多维数组不会初始化

时间:2016-09-14 00:01:29

标签: c++

我一直试图让它正常工作;但似乎我无法弄清楚这一点。我试图让游戏板正确初始化,但它一直在说<error reading characters of string>

using namespace std;

int main()
{

    board show;
    show.init();
    show.printing();

}


class board {

public:
    void init(){

        string Board[8][9] = {
            { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
            { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
        };
    }

    void printing(){

        string character = "*";

        int position[2] = { 2, 2 };
        // Draw the grid once
        for (int i = 0; i < 8; i++){
            for (int j = 0; j < 9; j++){
                if (i == position[0] && j == position[1])
                    cout << character;
                else
                    cout <<  Board[8][9];
                cout << " ";
            }
            cout << endl;
        }
    }

private:
    string Board[8][9];
};

2 个答案:

答案 0 :(得分:2)

这很简单:你有半个解决方案: 只需使用for循环来复制值

void A::init()
{
    string Board[8][9] = {
        { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 ", " 0 " },
        { "C56", "C15", "C21", "C62", "C11", "C62", "C21", "C15", "C56" },
    };

    for(int i(0); i < 8; i++)
    {
        for(int j(0); j < 9; j++)
            this->Board[i][j] = Board[i][j];        
    }
}

答案 1 :(得分:0)

init方法中,您创建了一个新的本地变量。您不是指实例变量,因此在printing方法中,变量未初始化。

而不是

string Board[8][9] = // ... initialization code

你应该写

this->Board = // ... initialization code

或只是

Board = // ... initialization code

您可以阅读有关变量类型here的更多信息。