用C ++创建动态对象的动态数组 [英] Creation of Dynamic Array of Dynamic Objects in C++

查看:94
本文介绍了用C ++创建动态对象的动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何创建动态对象数组.

I know how to create a array of dynamic objects.

例如,类名称为Stock.

For example, the class name is Stock.

Stock *stockArray[4];
for(int i = 0 ; i < 4;i++)
{
   stockArray[i] = new Stock();
}

如何将其更改为动态对象的动态数组?

How do you change this to dynamic array of dynamic objects?

我尝试过的事情:

库存 stockArrayPointer =新库存库存[4];

它不起作用,错误是不能使用Stock的值**初始化Stock类型的实体.

It doesn't work and the error is "The value of Stock** cannot be used to initalize an entity of type Stock.

第二个问题是创建动态对象的动态数组之后,访问数组中的指针的语法是什么.

Second question is after the creation of dynamic array of dynamic objects, what is the syntax to access the pointers in the array.

现在,我使用stockArray [i] = new Stock();这种变化将如何?

Now, I use stockArray[i] = new Stock(); How will this change?

对此需要一些指导...

Need some guidance on this...

推荐答案

如果您使用的是c ++,那么您不应该重新发明轮子,只需使用

If you are using c++ then you shouldn't reinvent the wheel, just use vectors:

#include <vector>

std::vector< std::vector< Stock > > StockVector;

// do this as many times as you wish
StockVector.push_back( std::vector< Stock >() );

// Now you are adding a stock to the i-th stockarray
StockVector[i].push_back( Stock() );

我不明白您的问题,如果您只想在堆上分配数组并分配数组,请使用:

I didn't understand your question, if you just want to have and array of arrays allocated on the heap just use:

Stock** StockArrayArray = new Stock*[n]; // where n is number of arrays to create
for( int  i = 0; i < n; ++i )
{
    StockArrayArray[i] = new Stock[25];
}

// for freeing
for( int i = 0; i < n; ++i )
{
    delete[] StockArrayArray[i];
}
delete[] StockArrayArray;

这篇关于用C ++创建动态对象的动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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