C++创建对象数组
Create array of objects C++
我正在尝试用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;
}
相关文章:
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何使用指针传递给函数的数组中对象的函数成员
- 在c++中为double类型的数组创建一个unique_ptr
- 如何从预定义的数组创建某些元素数组
- 基于数组的列表 - 动态数组创建时出错
- 从 UTF-8 字节数组创建字符串?
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- C++ 从名称数组创建对象
- 具有公共内存区域的类似数组的对象
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 如何声明包含整数数组的对象
- 从 std::数组创建十六进制代表
- 在 C++ 结构内声明的数组 A[1] 创建多个实例
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- C++包含使用 unique_ptr 的字符数组的对象
- 如何初始化数组指针对象
- 使用具有唯一随机数的结构数组创建多个对象
- 返回在各种语言的函数中创建的数组和对象
- C++:通过数组创建的对象,但如何传递参数