C++ - 这个双指针/数组结构的真正含义是什么?我很难想象

标签 c++ arrays pointers data-structures

这是在 C++ 代码中

YInterface ** Y_list;

int numberofYInterfaces;

然后

numberofYInterfaces=1;

Y_list = new YInterface *[numberofYInterfaces];        //What ??????

我很难想象 Y_list 的结构?然后想象一下当 numberofYInterfaces 变得超过 1,甚至 2 时我会感到困惑吗?

糟糕抱歉,我忘了写下面的声明:

Y_list[i]= new AnotherClass();

//稍后补充到我原来的问题。感谢 Eric Fortin 的提醒。 注:AnotherClass继承自YInterface。

感谢任何帮助

最佳答案

当您声明 Y_list 时,您会得到一个包含未指定值的单个变量:

Y_list
+-------+
|       |
+-------+

When you assign it with new[], it points to whatever new[] allocated, which in this case is an array of pointers:

Y_list         array
+-------+     +-------+
|   o---+---->|       |
+-------+     +-------+
              |       |
              +-------+
              |       |
              +-------+
              |       |
              +-------+
              |       |
              +-------+

At that point, you don't yet have any YInterface objects. You just have space allocated to hold pointers to them, should they ever exist.

Finally, you assign a value to one of the elements Y_list[i] = new AnotherClass. That's when a YInterface descendant exists, but you only have one so far. Run that code in a loop and you'll get multiple instances. But you still just have one array, and one pointer to that array.

Y_list         array         AnotherClass
+-------+     +-------+     +-------+
|   o---+---->|   o---+---->|       |
+-------+     +-------+     |       |
              |       |     |       |
              +-------+     |       |
              |       |     |       |
              +-------+     +-------+
              |       |
              +-------+
              |       |
              +-------+

To free all this, remember to have one delete statement for each new statement you had, and one delete[] for each new[]:

delete Y_list[i];

delete[] Y_list;

关于C++ - 这个双指针/数组结构的真正含义是什么?我很难想象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4924212/

相关文章:

c++ - 是否可以将 Windows 位图绘制到 cairo 表面?

c++ - 仅测试集合集合中的每个元素一次

c++ - 如果由于接收对象的线程已结束而未处理 Qt 信号,是否会删除参数?

Java - 使用键/值对制作对象?

php - 正则表达式数组与字符串问题

对二维结构体的指针感到困惑

c++ - 生成随机字母数组并计算出现次数

Objective-C 损坏的指针和回调问题

c# - 为什么 IntPtr 不需要 unsafe 关键字?

c - 二维数组正在截断一些字符