使用双指针动态分配。
|
我有一个基类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函数,则不应将数据分配给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时,它将自动创建Toy类型的指针(ptr)。
我希望我已经很好地解释了我试图在此代码中实现的内容。
请在这方面帮助我。
谢谢
没有找到相关结果
已邀请:
2 个回复
珊畴炮贩号
其中
保存所需的you5ѭ指针的数量。增大数组很困难,但是可以做到:
请注意,如果分配失败,旧的ѭ7和其中的所有指针都不会清除。确实,如果您想要一个增长的数组,请改用
:
并加上ѭ10toys的玩具。 不要忘了每个single12ѭ11,并采用第一种方法将
13。 继承可以处理各种数据。
念炯