我有一个基类 Toy 和派生类 Toy_remote_car 和 Toy_battery_car。

我正在这样做:

Toy** ptr;
ptr=new Toy*;
ptr[0]=new Toy_remote_car[1];
ptr[1]=new Toy_battery_car[1];/*this is completely wrong according to my teacher because i never created ptr[1]. Instead this is a misuse of memory according to him.*/

上面的代码(ptr=new Toy*) 正在创建一个Toy(ptr[0]) 类型的指针,它包含派生类Toy_remote_car 的对象。

现在我想写这样的代码:

->不应预定义玩具类型指针的数量。

->相反,我会调用一个 add_toy 函数,它会创建一个指向我想要的对象类型的 ptr。此外,如果我再次调用 add_toy 函数,它不应该将数据分配给之前的 ptr,而是应该创建一个新的 ptr。以下约定可能会有所帮助:
ptr[0]=new Toy_remote_car[1];
/*we want to add more toys so add_toy function called. A check is applied.*/
/*The check checks that ptr[0] already contains a value so it creates another pointer ptr[1]*/
ptr[1]=new Toy_battery_car[1];

->此外,我将能够访问所有以前的数据。简而言之:
ptr[0]//contains one type of data.
ptr[1]//contains another type.
//and so on

->因此,每当添加新玩具时,它都会自动创建一个 Toy 类型的指针(ptr)。

我希望我已经很好地解释了我试图在这段代码中实现的内容。

请在这方面帮助我。

谢谢

最佳答案

Toy **ptr = new Toy *[n];

其中 n 保存您想要的 Toy 指针的数量。增加数组很困难,但可以做到:
// Add x to toypp, an array of n pointers
// very stupid, linear-time algorithm
Toy **add_toy(Toy *x, Toy **toypp, size_t n)
{
    Toy **new_toypp = new Toy*[n+1];

    // copy the old array's contents
    for (size_t i=0; i<n; i++)
         new_toypp[i] = toypp[i];
    toypp[n] = x;

    // clean up
    delete[] toypp;

    return new_toypp;
}

请注意,如果分配失败,则不会清除旧的 toypp 和其中的所有指针。真的,如果您想要一个增长的数组,请改用 vector<Toy*>:
vector<Toy*> toy_ptrs(n);

并使用 push_back 添加玩具。

不要忘记对每个 delete 进行 Toy* ,并使用第一种方法对 delete[] 进行 Toy**

可以通过继承来处理各种数据。

关于c++ - 使用双指针动态分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5721728/

10-11 22:16
查看更多