如何管理指向对象的指针数组? [英] How to manage an array of pointers to objects?

查看:30
本文介绍了如何管理指向对象的指针数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对对象的指针数组有问题:(..

I have a problem with an array of pointers to objects :(..

我需要生成对象的动态矢量,然后将其返回以便在另一个类中对其进行操作.在下面的代码中有事件类是抽象的,而CarArrival继承自该类,并且可以实例化.

I need to generate a dynamic vector of object and then return it in order to manipulate it in another class. In the code below there is Event class that is abstract and CarArrival that inherits from it and can be instantiated.

在生成并填充数组的类中,我具有以下功能:

Inside the class that generate and fill the array I have this function:

Event** EventGenerator::getEvents() {

Event* cars[EVENTS];

for (int i=0; i<EVENTS; i++) {
    cars[i] = new CarArrival(generator->getNextNumber(8,(float)sqrt(0.4)));
}

sort(cars, cars+(EVENTS), Event::cmp);

return cars;

}

我以这种方式在其他类中调用此函数:

I invoke this function in onther class in this way:

Event** cars = generator->getEvents();

for(int i=0; i<EVENTS; i++) {
    cout << i <<":" << (*cars)[i]->getScheduleTime() << endl;
}


在打印第一个元素后,出现细分错误".


after the print of the first element i get "Segmentation Fault".

我已经在线阅读了一些内容,并且我理解我错了,因为(* cars)评估为指向数组第一个元素的指针,实际上我可以打印第一个元素,而不能打印其他元素,但是我无法弄清楚如何访问第二个类中数组的每个元素.

I have read some things online and I understand that I mistake since (*cars) evaluates to a pointer to the first element of the array, in fact I can print the first element and not the other, but I cannot figure out how to access every element of the array in the second class.

我怎么面对这个?

感谢所有人

阿尔贝托

推荐答案

我建议您改用 std :: vector< Event *> .这样您将节省很多痛苦.它负责后台所有烦人的内存管理,您可以轻松地将任意数量的项目放入其中.在这种情况下,最好的部分是,您可以简单地返回一个 vector ,这对于常规数组是不安全的.

I'd suggest that you use a std::vector<Event*> instead. You'll save a lot of pain this way. It takes care of all the nasty memory management in the background, and you can easily push any number of items into it. The best part in your case is, that you can simply return a vector which is not safe with a normal array.

您的 Event *汽车[EVENTS]; 也在您的函数中本地声明.完成后,它就不存在了,这可能会导致您的Segfault.您必须使用 new 动态分配数组,但是仍然可以使用 std :: vector 尝试使用它,请参见

Also your Event* cars[EVENTS]; is declared locally in you function. After you have finished it, it ceases to exist, which might cause your Segfault. You'd have to dynamically allocate the array with new, but still, try it with std::vector, see the documentation here.

示例用法:

std::vector<Event*> EventGenerator::getEvents() {
    std::vector<Event*> cars;
    for (int i=0; i<EVENTS; i++) {
        cars.push_back(new CarArrival(generator->getNextNumber(8,(float)sqrt(0.4))));
    }

    sort(cars.begin(), cars.end(), Event::cmp);

    return cars;
}


std::vector<Event*> cars = generator->getEvents();

for(int i=0; i<cars.size(); i++) {
    cout << i <<":" << (*cars)[i]->getScheduleTime() << endl;
}

这篇关于如何管理指向对象的指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆