当我打印我的字段时它可以工作,但是当我更改一个值时,数组似乎被重置。我想我在错误的地方宣布我的字符串veld[10][11]
,但我并不害羞。
还得到了我的班级speelveld.h
的属性。
谢谢
#include "speelveld.h"
#include "Schip.h"
void spelbord::printVeld(){
//spelbord::zetBoot();
string veld[10][11]= {
{ "A", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "B", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "C", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "D", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "E", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "F", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "G", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "H", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "I", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " },
{ "J", " ", " ", " ", " ", " ", " ", " ", " ", " ", " " }
};
cout << " 1 2 3 4 5 6 7 8 9 10" << endl;
for (int i = 0; i < 10; i++){
cout << " +-+-+-+-+-+-+-+-+-+-+" << endl;
for (int j = 0; j < 11; j++){
cout << veld[i][j] << "|" << flush;
}
cout << endl;
}
cout << " +-+-+-+-+-+-+-+-+-+-+" << endl;
}
void spelbord::zetBoot(){
string veld[10][11];
cout << "Wat is de eerste coordinaat van je vliegdekschip? (bv: a1) " << flush;
cin >> vliegdekschip1;
y = vliegdekschip1[0];
x = vliegdekschip1[1];
cout << y << endl;
cout << x << endl;
spelbord::checkpos();
}
void spelbord::checkpos(){
if (y == 97){
if (x == 49){
veld[0][1] = "O";
spelbord::printVeld();
}
{
{
答案 0 :(得分:2)
对于我的其余部分,我认为您的班级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();
}
}
总结您始终显示新初始化的变量。不是您在spelbord::checkpos
中修改的那个。
/* 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. */
}
这次成员只在构建对象时初始化一次,然后修改并显示该成员。