gpt4 book ai didi

c++ - while 循环外的变量在重新分配时变为 NULL

转载 作者:行者123 更新时间:2023-11-28 03:20:05 25 4
gpt4 key购买 nike

<分区>

我问的第二个问题是关于同一个程序。感觉不对,但没办法。

这是导致问题的代码:

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<<"\n\nYou have found the exit."<<endl;
}
return 0;
};

正如您所想,这个“当前”变量存储当前对象。在开始 while 循环之前,我将它设置为对象 A。在 while 循环结束时,我通过 case 语句将其更改为其他内容。

问题是,当循环回到开始时,'current' 变为 NULL。当我尝试调用 current->message() 时,它失败了,因为“current”里面什么都没有。

感觉我在这里犯了一些基本错误。但是我已经在这个问题上苦苦思索了 2 天,但没有任何效果。

谁能给我解释一下这里发生了什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com