C++/MFC中如何给多级嵌套的结构体数组动态地分配内存

benma123 2018-05-22 03:34:48
在数据结构DataType.h头文件中代码如下:
//结构体:组(其下一级为PLANE:面)
typedef struct _GROUP_
{
unsigned int uGroupRow; //记录组的行数
unsigned int uGroupCol; //记录组的列数
PLANE *pPlane;
_GROUP_(unsigned int uSetGroupR, unsigned int uSetGroupC)
{
pPlane = new PLANE[uSetGroupR * uSetGroupC];
uGroupRow = uSetGroupR; uGroupCol = uSetGroupC;
}
_GROUP_(void)
{
uGroupRow = 0;
uGroupCol = 0;
pPlane = NULL;
}
~_GROUP_()
{
if (pPlane)
{
delete pPlane;
}
}
PLANE & operator [](unsigned int index)
{
return pPlane[index];
}
}GROUP;

//结构体:面(其上一级为GROUP:组,下一级为LINE:线)
typedef struct _PLANE_
{
unsigned int uPlaneRow; //记录组的行数
unsigned int uPlaneCol; //记录组的列数
LINE *pLine;
_PLANE_(unsigned int uSetPlaneR, unsigned int uSetPlaneC)
{
pLine = new LINE[uSetPlaneR * uSetPlaneC];
uPlaneRow = uSetPlaneR; uPlaneCol = uSetPlaneC;
}
_PLANE_(void)
{
uPlaneRow = 0;
uPlaneCol = 0;
pLine = NULL;
}
~_PLANE_()
{
if (pLine)
{
delete pLine;
}
}
LINE & operator [](unsigned int index)
{
return pLine[index];
}
}PLANE;

//结构体:线(其上一级为PLANE:面,下一级为POINT:点)
typedef struct _LINE_
{
unsigned int uPointNum; //记录点数量
float fCenterX; //中心坐标
float fCenterY;
POINT* pPoint;
_LINE_(unsigned int uSetPoint)
{
pPoint = new POINT[uSetPoint];
if (!pPoint)
{
exit(0);
}
this->uPointNum = uSetPoint;
}
_LINE_(void)
{
fCenterX = 0;
fCenterY = 0;
pPoint = NULL;
}
~_LINE_()
{
if (pPoint)
{
delete pPoint;
}
uPointNum = 0;
}
POINT & operator [](unsigned int index)
{
return pPoint[index];
}
}LINE;

//结构体:点(其上一级为LINE:线)
typedef struct _POINT_
{
float fX; //点坐标
float fY;
_POINT_()
{
fX = 0;
fY = 0;
}
}POINT;

在主程序cpp文件中代码如下:
m_uGroupRow = 7; //组:行数
m_uGroupCol = 8; //组:列数
m_uPlaneRow = 500; //面:行数
m_uPlaneCol = 500; //面:列数
m_uLineNum = m_uPlaneRow * m_uPlaneCol; //线:个数
m_uPointNum = 5; //点:个数

// 定义一个结构体,传入变量参数,用于动态分配结构体数组内存空间
GROUP group_D(m_uGroupRow, m_uGroupCol);

//说明:
我这样做是为了通过界面传入组列数/行数、面列数/行数等,动态地分配内存空间,最后可以遍历任何一个point。例如组行数为7,列数为8,则定义group_D时传入7和8,则执行Group结构体中的代码pPlane = new PLANE[uSetGroupR * uSetGroupC];时,会让uSetGroupR = 7,uSetGroupC = 8,动态地分配设定的数组空间。
然后二级结构体中,传入m_uPlaneRow、m_uPlaneCol 的值,执行PLANE结构体中的自定义构造函数时(即pLine = new LINE[uSetPlaneR * uSetPlaneC];)又动态分配设定内存空间。以此类推。

//问题:
我在此定义结构体时写为:GROUP group_D(m_uGroupRow, m_uGroupCol);只传入了一级结构体动态分配空间的大小m_uGroupRow和m_uGroupCol,那么怎么继续传入嵌套的二级、三级结构体中动态分配空间的变量(即m_uPlaneRow 、m_uPlaneCol 、m_uPointNum )?结构体的编写定义有错吗?感谢各位大神指点!
...全文
983 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-05-22
  • 打赏
  • 举报
回复
百度搜相关关键字。

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧