2016-12-16 61 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它回答你的问题吗?还是还有一些你想知道的事情? –