繁体   English   中英

如何使用用户定义的值初始化对象数组并从用户那里获取输入?

[英]How to initialize array of objects with user defined values and take input from user?

#include <iostream>
using namespace std;

class car{

string owner;
string car_num;
string issue_date;

car(string o, string cn, string id)
{
    owner = o;
    car_num  = cn;
    issue_date = id;
}

void getInfo()
{
    cout << "Car's Owner's Name : " << owner << endl;
    cout << "Cars' Number : " << car_num << endl;
    cout << "Car's Issue Date : " << issue_date << endl;
}

};

int main()
{
    
    int n;
    cout << "Enter total number of cars stored in your garage : \n";
    cin >> n;
    car c1[n]; //incomplete code due to the issue


    return 0;
}

在这里,我想从用户那里获取汽车总数。 并且还想通过使用循环从用户那里获取汽车属性。 但是在使用构造函数时我该怎么做呢?

我的建议是不要过度使用构造函数。 它应该构建,并且真的应该只构建。 在您的情况下,您甚至不需要构造函数。 而是添加一个新的 function 来进行初始化。 传统是使用运算符>> ,这通常是外部function。
至于环...

车c1[n]; //由于问题导致代码不完整

是不合法的 C++ (尽管它在 C 和许多也是 C 编译器的编译器中是允许的)
最好使用向量。 所以...

    vector<car> c1(n);
    for (auto& c : c1) 
       cin >> c;

一种高级技术是使用istream 迭代器,它允许您使用 std::copy 等算法,为向量的每个成员调用输入运算符。 然而,它真的不是必需的,只是一个“nicety”

改用指针数组。例如

car* c1[n];

//incomplete part
for(int i = 0; i < n; i++){
    //take input and process
    c1[i] = new car(//put processed inputs here);
    }

PS:我觉得我在某个地方犯了错误,但现在无法测试。 如果它不起作用,请在此处发表评论。

您可以将循环与 std::cin 一起使用,例如for(int i=0;i<n;++i){std::cin<<num;} 我在代码中提到的 'n' 也可以由 std::cin 赋值

int n;
std::cin>>n;
car* cars=new car[n];
for(int i=0;i<n;++i)
{
   std::getline(cars[i].owner,std::cin);
   // and something other you'd like to do, like to test its validity
}

车c1[n]; //由于问题导致代码不完整

实际上,您在这里有两个问题:

  1. 标准 C++ 中不允许使用可变长度 Arrays (VLA)。 它们在标准 C 中是可选的,并且被一些 C++ 编译器作为扩展支持。
  2. 你不能有一个没有默认构造函数的对象数组(除非你完全初始化它)。

假设您不想更改 class (除了插入public:在数据成员之后),现代解决方案应该使用std::vector

    std::vector<car> c;

    //incomplete part
    for(int i = 0; i < n; i++){
        std::string owner, car_num, issue_date;
        //TODO: get the strings from the user here ...
        c = c.emplace_back(owner, car_num, issue_date);
        }
#include <iostream>
using namespace std;

class car{
public:
string owner;
string car_num;
string issue_date;

void cars(string o, string cn, string id)
{
    owner = o;
    car_num  = cn;
    issue_date = id;
    getInfo();
}

void getInfo()
{
    cout << "Car's Owner's Name : " << owner << endl;
    cout << "Cars' Number : " << car_num << endl;
    cout << "Car's Issue Date : " << issue_date << endl;
}

};

int main()
{
    
    int n;
    string a,b,c;
    cout << "Enter total number of cars stored in your garage : \n";
    cin >> n;
    car cas[n]; //incomplete code due to the issue
    for(int i=0;i<n;++i)
    {
     cout<<"value1:";
     cin>>a;
     cout<<"value2:";
     cin>>b;
     cout<<"value3:";
     cin>>c;
     cas[i].cars(a,b,c);
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM