2016-12-16 59 views
-3

好吧我搜索的問題,但無法得到我的答案,或沒有使用適當的術語。C++我如何直接通過程序自動創建對象

if(choice == 2){ 
    string tempName, tempAddress; int tempNic,tempContact; 
    cout << "\n\t\t*\tWelcome to Our Sponsor Registeration Section\t*\n\n"; 
    cout << "Please enter your name : "; cin>>tempName; 
    cout << "Please enter your National Identity Card Number : "; cin>>tempNic; 
    cout << "Please enter your Contact Number : "; cin>>tempContact; 
    cout << "Please enter your Address : "; cin>>tempAddress; 
    // prototype Sponsor(string n, string add, int nic_n, int phone) constructor 
    Sponsor (Constructor goes here) // how to make many objects now? 
} 

代碼粘貼在這裏https://codeshare.io/aVxl42

檢測線69我要去的地方使用構造函數添加值,這個我可以加1個對象,但我怎麼辦這樣,如果使用程序的人想要添加更多的對象嗎?

我知道我需要封裝61和70之間的東西。 請幫我解決這個問題。

+0

請將*相關*代碼直接包含在問題主體中。如果我們應該閱讀特殊文字,請用例如註釋。想想如果鏈接消失會發生什麼,這將使問題完全沒有價值。請[請閱讀如何提出良好問題](http://stackoverflow.com/help/how-to-ask),並學習如何創建[最小,完整和可驗證示例](http:// stackoverflow。 COM /幫助/ MCVE)。 –

+0

我不太清楚你想做什麼,但列表(http://www.cplusplus.com/reference/list/list/)或矢量(http://www.cplusplus.com/reference/vector/vector/vector /)可能會有所幫助。 – Lehue

+0

將用戶輸入請求置於循環中,並將創建的贊助者添加到向量中。 – DrPepperJo

回答

0

我猜你想讓它循環?我會建議一個while循環。 我沒有永遠使用矢量(教授禁止它),所以我可能會犯一些錯誤,但你會得到總體的觀點。

bool stop = false; //This is to check after each loop if it should continue or not 
char contChoice; 
vector<Sponsor> sponsors; 

while(!stop){ 
    if(choice == 2){ 
     string tempName, tempAddress; int tempNic,tempContact; 
     cout << "\n\t\t*\tWelcome to Our Sponsor Registeration Section\t*\n\n"; 
     cout << "Please enter your name : "; cin>>tempName; 
     cout << "Please enter your National Identity Card Number : "; cin>>tempNic; 
     cout << "Please enter your Contact Number : "; cin>>tempContact; 
     cout << "Please enter your Address : "; cin>>tempAddress; 
     // prototype Sponsor(string n, string add, int nic_n, int phone) constructor 
     sponsors.push_back(Sponsor(tempName, tempAddress, tempContact, tempNic)); 
     //Add whatever other arguments you want to pass in, in whatever order 
     cout << "Do you want to continue? [Y/N]: "; cin>>contChoice; 
     if(contChoice == 'N' || contChoice == 'n') 
       stop = true; 
     else stop = false; //This isn't really necessary since it is false by default 
    } 
} 

但我也建議你至少在贊助商中做集合成員函數。您也可以使用動態數組並使其展開,而實際上比矢量更棘手。

+0

那麼我知道在哪裏放置循環。但是將對象添加到矢量中對我而言是新事物,那就是我被卡住的地方,當最終用戶從菜單中選擇用於添加用戶的選項時,我想要添加新對象,而不是實際預定義的編碼對象。 –

+0

@BaqarHussain它回答你的問題嗎?還是還有一些你想知道的事情? –