2016-04-24 71 views
0

什麼是創建動態(不知道這是否是正確的單詞)對象的最佳方式?例如,如果我運行以下命令:創建新的「動態」對象?

Person man[10]; 


cout << "MENU" << endl; 
cout << "1. Add a person to the list" << endl; 
cout << "2. Delete a person from the list" << endl; 
cout << "3. Change a person's information'" << endl; 
cout << "4. Locate a person by ID number" << endl; 
cout << "5. Locate a person by last name" << endl; 
cout << "6. Print the list on the screen" << endl; 
cout << "7. Load the list from a file" << endl; 
cout << "8. Save the list to a file" << endl; 
cout << "9. Exit the program" << endl; 

cin >> a; 

if (a == 1) { 
     if (i <= 10) { 

      Person man[i]; 
      cout << "Please enter your last name: " ; 
      cin >> last; 
      man[i].setLastName(last); 
      i++; 
      cout << man[i].getLastName(); 

     } 
} 

當我運行這一點,我可以進入我的姓,但是當我按ENTER鍵程序停止運行。這是什麼原因,並有沒有更好的方式來創建這些對象「配置文件」?

謝謝,如果這是一個愚蠢的問題,我很抱歉。

+0

'Person man [10];' - 您已經創建了10個'Person'對象。查找'std :: vector'。 – PaulMcKenzie

回答

0

原因是你的整個程序只需要輸入一個輸入cin >> a;然後檢查它是否等於1.在程序塊之後沒有什麼可做的事情。所以你的程序終止了。

如果你想編輯你的10人obj的所有名字和姓氏,你最好創建一個循環來做到這一點。 For循環,你可以谷歌for/while。

繼承人例如:

int i; 
    while(cin >> i) 
    { 
     if(i == 9) 
      return; 
     else if[....] 
    } 
+0

如果我添加: cout << man [i] .getLastName(); 它仍然退出。那是不是在給它做點什麼? –

+0

因爲我的朋友,即使你添加了cout << man [i] .getLastName();你的程序在你的屏幕上打印後仍然會退出> _> – JaNL

+0

你可以嘗試添加我提供給你的代碼,看看它是否有幫助 – JaNL

0

當你說動態,對象分配是通過新的運營商。在你的代碼中,數組已經被聲明瞭10個元素(靜態分配)。因此,在你的代碼中你沒有執行動態分配。 對於動態分配,添加一個可以返回一個新Person對象的函數。在這個函數中使用new運算符創建一個對象並返回這個對象。 這種方式可以動態添加新對象。

有關動態分配的更多詳細信息,請參閱new運算符。

+0

這個概念是有道理的,但我不確定你的意思是可以返回新的Person對象的函數。 –