这是在 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/