C++ 创建对象数组C++;

C++ 创建对象数组C++;,c++,class,object,C++,Class,Object,我试图在C++中创建一个类的对象数组。当我打印对象时,它跳过数组的第一个元素(a[0])。我读过很多论坛,但我找不到问题所在。谁能看见它 class driver { private: string name; string surname; string categories; int salary, hours; public: void reads(string &n, string &p, string &c, int &a

我试图在C++中创建一个类的对象数组。当我打印对象时,它跳过数组的第一个元素(a[0])。我读过很多论坛,但我找不到问题所在。谁能看见它

class driver
{
private:
    string name;
    string surname;
    string categories;
    int salary, hours;   
public: 
void reads(string &n, string &p, string &c, int &s, int &h)
{
    std::cout<<"\t\t Give information about driver:"<<std::endl;
    std::cout<<"\t\t---------------------------------------\n";
    std::cout<<"\tGive name: "; std::cin>>n;
    std::cout<<"\tGive surname: "; std::cin>>p;
    std::cout<<"\tGive categories of driver license: "; std::cin>>c;
    std::cout<<"\tHow much he is payd for hour: "; std::cin>>s;
    std::cout<<"\tHow many hours did "<<n<<" "<<p<<" works? "; std::cin>>h;
} 
void print()
{
    std::cout<<name<<" "<<surname<<" ";
    std::cout<<"has categories "<<categories<<endl;
    std::cout<<"Salary per hour is "<<salary<<endl;
    std::cout<<"Driver had worked "<<hours<<" hours"<<endl;
    std::cout<<"Full payment is "<<salariu*hlucru<<" $"<<endl;
}
};
int main()
{
   string n,p,c;
   int s,h,nr,i;
 cout<<"Give nr of drivers:"; cin>>nr;
 driver *a[nr];
 for(i=0;i<nr;i++)
 {
     a[i]=new driver(n,p,c,s,h);
     a[i]->reads(n,p,c,s,h);
     cout<<endl;
 }
 for(i=0;i<nr;i++)
 {
     a[i]->print();
     cout<<endl;
 }
类驱动程序
{
私人:
字符串名;
串姓;
字符串类别;
int工资,小时数;
公众:
无效读取(字符串和n、字符串和p、字符串和c、整数和s、整数和h)
{
std::cout您的
reads()
函数没有执行您期望的操作。它正在向
main()
字符串读取数据,然后将这些字符串传递给您创建的下一个对象。
您的
a[0]
有未初始化的成员,这就是您所看到的“未打印[0]”

您的代码可能更像这样:

void reads() {
    //all the std::cout calls should also be here
    std::cin >> name;
    std::cin >> surname; //etc. 
}
main()
中:

intmain()
{
国际天然气公司;
cout>nr;
driver*a=新驱动程序[nr];//改用std::vector!
对于(int i=0;icoutYour
reads()
函数不会更改
driver
类中的任何单个对象。您可以在
main
中更改字符串,然后将这些字符串传递给下一个对象。您的第一个
driver
对象具有未初始化的字段。
driver*a[nr]< C++ >使用VLA扩展无效。使用<代码> STD::向量< /代码>。驱动器构造函数丢失BTW.
int main()
{
    int nr;
    cout << "Give nr of drivers:"; 
    cin >> nr;
    driver* a = new driver[nr]; //use std::vector instead!
    for(int i = 0; i < nr; i++)
    {
        a[i].reads();
        cout<<endl;
    }
    for(int i = 0; i < nr; i++)
    {
        a[i].print();
        cout<<endl;
    }
    delete[] a;
}