我有一个基类玩具和派生类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 =新玩具*)是创造型玩具的单个指针(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
- >所以每当被增加了一个新玩具时,将自动创建型玩具的一个指针(PTR)。
我希望我已经很好地解释了我在这段代码中实现的内容。
请在这方面帮助我。
感谢
**为什么在这个世界上**你是否在免费店里分配指针?!?! – 2011-04-19 20:51:43