C++ 多维数组替换值

C++ 多维数组替换值,c++,multidimensional-array,C++,Multidimensional Array,当我打印字段时,它工作,但当我更改一个值时,数组似乎被重置。我想我在错误的地方声明了我的字符串veld[10][11],但我不是舒尔。 还将veld作为我的类的属性speelveld.h 谢谢 #包括“speelveld.h” #包括“Schip.h” void spelbord::printfeld(){ //spelbord::zetBoot(); 字符串级别[10][11]={ {“A”、、、、、、、、、、、、、、、、、、、、、、}, {“B”、、、、、、、、、、、、、、、、、、、、、、}

当我打印字段时,它工作,但当我更改一个值时,数组似乎被重置。我想我在错误的地方声明了我的字符串
veld[10][11]
,但我不是舒尔。 还将veld作为我的类的属性
speelveld.h
谢谢

#包括“speelveld.h”
#包括“Schip.h”
void spelbord::printfeld(){
//spelbord::zetBoot();
字符串级别[10][11]={
{“A”、、、、、、、、、、、、、、、、、、、、、、},
{“B”、、、、、、、、、、、、、、、、、、、、、、},
{“C”、、、、、、、、、、、、、、、、、、、、、、},
{“D”、、、、、、、、、、、、、、、、、、、、、、},
{“E”、、、、、、、、、、、、、、、、、、、、、、},
{“F”、、、、、、、、、、、、、、、、、、、、、、},
{“G”、、、、、、、、、、、、、、、、、、、、、、},
{“H”、、、、、、、、、、、、、、、、、、、、、、、},
{“I”、、、、、、、、、、、、、、、、、、、、、、},
{J',,,,,,,,,,,,,,,,,,,,,,}
};
cout对于我的其余答案,我假设您的类
spelbord
具有
veld
类型
string
的属性

问题 问题在于,在
spelbord::printVeld
函数中使用了局部变量:

void spelbord::printVeld()
{
    /* Initialize a 'new' local variable each time you pass here. */
    string veld[10][11] = {
        /* Initialization value. */
    }

    /* Print header. */
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 11; ++j)
            /* Refers to the variable just initialized. */
            cout << veld[i][j] << "|" << flush;
        cout << endl;
    }
    /* Print footer. */
}

void spelbord::checkpos()
{
    if (y == 97)
        if (x == 49)
        {
            /* Refers to the attribute 'veld' of the 'spelbord' object */
            veld[0][1] = "O";
            spelbord::printVeld();
        }
}

这一次,当构建对象时,该成员只初始化一次,您可以修改并显示该成员。

代码示例末尾的大括号看起来很奇怪。成员变量
veld
被同名的局部变量隐藏。或者为局部变量选择其他名称,请使用
This->veld
来访问成员变量,或者去掉名为
veld的局部变量,因为它们似乎不是必需的。
void spelbord::printVeld()
{
    /* Initialize a 'new' local variable each time you pass here. */
    string veld[10][11] = {
        /* Initialization value. */
    }

    /* Print header. */
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 11; ++j)
            /* Refers to the variable just initialized. */
            cout << veld[i][j] << "|" << flush;
        cout << endl;
    }
    /* Print footer. */
}

void spelbord::checkpos()
{
    if (y == 97)
        if (x == 49)
        {
            /* Refers to the attribute 'veld' of the 'spelbord' object */
            veld[0][1] = "O";
            spelbord::printVeld();
        }
}
/* Constructor. Used to initialize members. */
spelbord::spelbord()
{
    /* I don't use the constructor's prefered way of initialization because your 
       initialization value is huge. */
    veld = { /* Initialization. */ };
}

/* No local variable this time. */
void spelbord::printVeld()
{
    /* Print header. */
    for (int i = 0; i < 10; ++i)
    {
        for (int j = 0; j < 11; ++j)
            /* Refers to the member of the object. */
            cout << veld[i][j] << "|" << flush;
        cout << endl;
    }
    /* Print footer. */
}

void spelbord::checkpos()
{
    /* Same as before. */
}