2013-03-30 39 views
0

第二个问题我询问同一个程序。感觉不对,但无法提供帮助。while循环之外的变量在重新分配时变为NULL

这里是导致该问题的代码:

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天,而且没有任何效果。

任何人都可以给我一个解释,这里发生了什么?

+1

您可以在'current = current-> getPaths()[0];等表达式中重新赋值'current';''current''取决于'current- > getPaths()[0]' – SomeWittyUsername

+0

是的。而且我在赋值时检查了它,getPaths()[0]不是空的,'当前'肯定被赋值为getPaths()[x]的值。 – eltaro

+0

这些'cout << nesw [i] .c_str()<<“,”;'语句的输出是什么?你会得到全部4个,就像你期待的那样? – Tushar

回答

2

您在选择开关时缺少break声明。所以它总是使用“West”选项。您的单元格A中的西部为NULL。

+0

确实很好抓:) – SomeWittyUsername

+0

什么****:O解决了它!非常感谢! – eltaro