while循环外的变量在重新赋值时变为NULL

variable outside of while loop becomes NULL when re-assigned

本文关键字:赋值 NULL 新赋值 循环 变量 while      更新时间:2023-10-16

我问的第二个问题是关于同一个程序的。感觉不对,但又忍不住。

下面是导致问题的代码:

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