第二个问题我问同一个程序。感觉不对,但无法帮助它。
以下是导致问题的代码:
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-&gt; message()时,它会失败,因为'current'中没有任何内容。
感觉就像我在这里犯的一些基本错误。但是我现在已经在这个问题上猛烈抨击了2天而没有效果。
有谁能解释一下这里发生的事情?
答案 0 :(得分:2)
您的选择开关中缺少break
语句。所以它总是使用“西方”选项。单元格A中的西方为NULL。