C++创建对象数组

Create array of objects C++

本文关键字:数组 创建对象 C++      更新时间:2023-10-16

我正在尝试用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<<"tt Give information about driver:"<<std::endl;
std::cout<<"tt---------------------------------------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;
}

您的reads()函数没有执行预期操作。它向main()字符串读取数据,然后将这些字符串传递给您创建的下一个对象。
您的a[0]具有未初始化的成员,这就是您看到的"未打印 a[0]">

您的代码可能应该更像这样:

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

在您的main()

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;
}