带有类型指针的C++函数调用,参数混淆:不允许使用不完整的类型

C++ function call with type pointer, parameter confusion: incomplete type is not allowed

本文关键字:类型 不允许 用不完 指针 C++ 函数调用 参数      更新时间:2023-10-16

我正试着用C++来理解。我只给你一些小片段来帮助说明这个想法,而不会让事情变得复杂。顺便说一句,我只实现了这些方法,我不能更改设置或参数。

我有一个用于动态数组数据结构的类,它包含称为股票的对象:

typedef class Stock ArrayType;
class DynamicArray {
    ArrayType** items;
    int numberOfElements;
    ...
}

这是它的构造函数。我应该分配数组并添加一个项,然后设置元素的数量。

DynamicArray::DynamicArray(ArrayType* const item){
    Stock *items = NULL; // ... i guess? pointers to pointers confuse me
    // now im guessing i need to create a actual stock array and point the above pointer to it
    items = new Stock[1]; // ERROR: incomplete type is not allowed? I've tried several things, and cant get rid of the red squiggles
    this->numberOfElements = 1;
}

好的,有一些问题。首先,你必须包括Stock。编译器需要Stock的完整定义才能编译DynamicArray,因为我猜测内存分配的原因。

其次,您希望items成员值包含对在构造函数中创建的数组的引用。因此,与其在构造函数中定义Stock *items[1],不如将new语句的值直接分配给this->items;只要不在正在处理的任何函数中定义同名变量,就可以提交this->

最后,您将分配一个指针数组,因此使用以下语法:new ArrayType*[1]

此外,正如编码实践所指出的,您不应该在同一个源中混合使用typedef及其原始类型。所以我建议您在整个过程中使用ArrayType,或者根本不使用。