使用双指针进行动态分配 [英] Dynamic allocation with DOUBLE POINTERS

查看:80
本文介绍了使用双指针进行动态分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base class Toy and derived classes Toy_remote_car amd 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的对象.

The above code(ptr=new Toy*) is creating a single pointer of type Toy(ptr[0]) which contains the object of derived class Toy_remote_car.

现在我想编写这样的代码:

Now i want to write such a code:

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

->the number of Toy type pointers should not be predefined.

->相反,我将调用add_toy函数,该函数将创建一个指向我想要的对象类型的ptr.此外,如果我再次调用add_toy函数,则不应将数据分配给previos ptr,而应创建一个新的ptr.以下约定可能会有所帮助:

->instead i would call an add_toy function which would create a ptr that will point to the type of object i want. Furthermore if i call the add_toy function again, it should not assign the data to the previos ptr, but it should create a new ptr. The following convention may help:

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

->此外,我将能够访问所有之前的数据.简而言之:

->furthermore i would be able to access all the previous data. In short:

ptr[0]//contains one type of data.
ptr[1]//contains another type.
//and so on

->因此,每当添加新的Toy时,它将自动创建Toy类型的指针(ptr).

->so it would automatically create a pointer(ptr) of type Toy whenever a new Toy is being added.

我希望我已经很好地解释了我要在此代码中实现的内容.

I hope i have explained well what i am trying to implement in this code.

请在这方面帮助我.

谢谢

推荐答案

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

其中n保存所需的Toy指针的数量.增大数组很困难,但是可以做到这一点:

where n holds the number of Toy pointers you want. Growing the array is hard, but it can be done:

// 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*>代替:

Note the if the allocation fails, the old toypp and all pointers in it are not cleaned up. Really, if you want an array that grows, use a vector<Toy*> instead:

vector<Toy*> toy_ptrs(n);

并添加带有push_back的玩具.

别忘了每个Toy*delete,并采用第一种方法,delete[] Toy**.

Don't forget to delete every single Toy*, and with the first method, to delete[] the Toy**.

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

Handling various kinds of data can be done with inheritance.

这篇关于使用双指针进行动态分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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