【问题标题】:C++ How can i create Object automatically via program directlyC ++如何直接通过程序自动创建对象
【发布时间】:2017-05-02 04:16:05
【问题描述】:

好的,我搜索了问题,但找不到答案,或者没有使用合适的术语。

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 之间的东西。 请帮我解决这个问题。

【问题讨论】:

标签: c++ oop object constructor


【解决方案1】:

我猜你想让它循环?我建议一个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
    }
}

但我也建议您至少在 Sponsor 中创建集合成员函数。您还可以使用动态数组并使其展开,这比向量更棘手,实际上更棘手。

【讨论】:

  • 我知道在哪里放置循环。但是将对象添加到向量中对我来说是新事物,这就是当最终用户从菜单中选择选项以添加用户而不是预定义的编码对象时,我被困在我想要添加新对象的地方。
  • @BaqarHussain 它回答了你的问题吗?还是您还有什么疑惑?
猜你喜欢
  • 1970-01-01
  • 2015-04-29
  • 2022-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多