0

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

这是导致问题的代码:

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”中没有任何内容。

感觉就像我在这里犯的一些基本错误。但是我已经在这个问题上抨击了两天,但没有任何效果。

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

4

1 回答 1

2

You are missing break statement in your choice switch. So it always uses "West" option. The west is NULL in your cell A.

于 2013-03-30T06:57:36.423 回答