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

查看:35
本文介绍了在 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?

我尝试了什么:

Stock stockArrayPointer = new Stock stock[4];

Stock stockArrayPointer = new Stock stock[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天全站免登陆