我正在尝试在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;
}
答案 0 :(得分:1)
您的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;
}