2013-03-30 30 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