while循环外的变量在重新赋值时变为NULL
variable outside of while loop becomes NULL when re-assigned
我问的第二个问题是关于同一个程序的。感觉不对,但又忍不住。
下面是导致问题的代码:
int main()
{
Link* link = new Link();
Instance* A = new Instance('A');
Instance* B = new Instance('B');
Instance* C = new Instance('C');
Instance* D = new Instance('D');
Instance* E = new Instance('E');
Instance* F = new Instance('F');
Instance* G = new Instance('G');
Instance* H = new Instance('H');
Instance* I = new Instance('I');
Instance* J = new Instance('J');
Instance* K = new Instance('K');
Instance* L = new Instance('L');
Instance* current= new Instance('X');
A->setNearbyObjects(NULL,B,E,NULL);
B->setNearbyObjects(NULL,NULL,F,A);
C->setNearbyObjects(NULL,D,G,NULL);
D->setNearbyObjects(NULL,NULL,NULL,C);
E->setNearbyObjects(A,NULL,I,NULL);
F->setNearbyObjects(B,G,NULL,NULL);
G->setNearbyObjects(C,H,K,F);
H->setNearbyObjects(NULL,NULL,L,G);
I->setNearbyObjects(E,J,NULL,NULL);
J->setNearbyObjects(NULL,NULL,NULL,I);
K->setNearbyObjects(G,NULL,NULL,NULL);
L->setNearbyObjects(H,NULL,NULL,NULL);
string nesw[4] = {"(N)orth","(E)ast","(S)outh","(W)est"};
char choice='X';
current=A;
while((current!=L)&&(choice!='Q'))
{
current->message();
cout<<"You can go ";
for(int i=0;i<current->getPaths().size();i++)
{
if(current->getPaths()[i]!=NULL)
{
cout<<nesw[i].c_str()<<", ";
}
}
cout<<"or (Q)uit"<<endl;
cin>>choice;
choice=toupper(choice);
while((choice!='N')&&(choice!='E')&&(choice!='S')&&(choice!='W')&&(choice!='Q'))
{
cout<<"Choice: "<<choice<<endl;
cout<<"Invalid input. Try again..."<<endl;
cin>>choice;
choice=toupper(choice);
}
switch(choice)
{
case 'N':
current=current->getPaths()[0];
case 'E':
current=current->getPaths()[1];
case 'S':
current=current->getPaths()[2];
case 'W':
current=current->getPaths()[3];
default:
break;
}
}
if(current==L)
{
cout<<"nnYou have found the exit."<<endl;
}
return 0;
};
这个'current'变量存储当前对象,正如你所想的那样。在开始while循环之前,我把它设为对象A。在while循环结束时,我通过case语句将其更改为其他内容。
问题是,当循环回到开始时,'current'变为NULL。当我尝试调用current->message()时,它会失败,因为'current'里面没有任何内容。
感觉我在这里犯了一些基本的错误。但是我已经为这个问题绞尽脑汁两天了,一点效果也没有。
谁能给我解释一下这里发生了什么?选择开关中缺少break
语句。所以它总是使用"西"选项。单元格a中的west为NULL
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 在 Json::Value in JsonCpp 中赋值 [null]
- 赋值null中的不兼容类型
- C++-将null赋值给std::字符串
- 赋值运算符c++NULL赋值
- 赋值时执行char*,以null结束String
- 赋值给允许NULL成员的数组,而不使用堆
- 如果不为null,则为指针赋值
- 是否有必要在使用临时字符串值后将其赋值为null ?
- 我应该检查NULL在我的赋值操作符
- 是否应该将构造函数体中赋值的指针成员初始化为NULL ?
- 每次在链表中调用insert_node()函数时,Head都被赋值为Null
- while循环外的变量在重新赋值时变为NULL
- 通过解引用NULL指针来赋值引用