加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用双指针进行动态分配

发布时间:2020-12-16 09:34:09 所属栏目:百科 来源:网络整理
导读:我有一个基类玩具和派生类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]. Instea
我有一个基类玩具和派生类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函数,它不应该将数据分配给previos 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包含您想要的玩具指针数量.增长阵列很难,但可以做到:

// 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及其中的所有指针都不会被清除.实际上,如果你想要一个增长的数组,请使用向量< Toy *>代替:

vector<Toy*> toy_ptrs(n);

并使用push_back添加玩具.

不要忘记删除每一个玩具*,并使用第一种方法删除[]玩具**.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读