将函数中的对象添加到动态指针数组中 [英] Add object in function to dynamic array of pointers

查看:100
本文介绍了将函数中的对象添加到动态指针数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

课程:

主席;

BigChair; (没有天真)



Chair.h:

int _bigChairsLength;

BigChair ** _bigChairs;



Chair.cpp:

Classes:
Chair;
BigChair; (no innherit)

Chair.h:
int _bigChairsLength;
BigChair** _bigChairs;

Chair.cpp:

void Chair::AddBigchair(string name, string color) // It must get params and not BigChair
{
     BigChair** temp = _bigChairs;
     _bigChairsLength++;
     _bigChairs = new BigChair*[_bigChairsLength];

     for (int i=0; i<_bigChairsLength - 1; i++)
     {
         _bigChairs[i] = temp[i];
     }

     delete [] temp;

     BigChair newBigChair(name, color);
     _bigChairs[_bigChiarsLength - 1] = &newBigChair;
              // (pointer to function variable??? how to add?
}

推荐答案

你的新数组获取一个局部变量的指针(来自堆栈而不是来自堆的元素)这个变量被破坏,指针指向垃圾。事实上,它指向一些最终会保存其他数据的内存,你将彻底破坏程序内存 - 迟早会发生不可预测的崩溃...

修复:

Your new array gets a pointer of a local variable (an element from the stack instead of from the heap). That variable gets destroyed and the pointer points to garbage. In fact, it points to some memory that will eventually hold other data and you will severly corrupt the program memory - unpredictable crash sooner or later...
Fix:
_bigChairs[_bigChiarsLength - 1] = new BigChair(name, color);



这是一个同性恋作业还是面试问题?这是如此基本。

干杯

Andi



PS:使用合适的STL容器(例如 vector )而不是指针指针。例如 std :: vector< BigChair> (或 std :: vector< BigChair *> ,取决于你的用法)。整个函数将折叠为 mvVector.push_back(BigChair(名称,颜色));


Is this a homweork assignment or an interview question? This is so basic.
Cheers
Andi

PS: use a suitable STL container (e.g. a vector) instead of a pointer of pointer. E.g. std::vector<BigChair> (or std::vector<BigChair*>, depends on you usage). The whole function would collaps to mvVector.push_back(BigChair(name, color));.


这篇关于将函数中的对象添加到动态指针数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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