【发布时间】:2021-04-09 02:14:02
【问题描述】:
首先,我是 C++ 的菜鸟,所以我很有可能犯了一个愚蠢的错误。但是我无法弄清楚问题是什么。
我有一个名为State 的对象类,我创建了一个名为List 的自定义类来存储、添加和删除State 对象实例的指针引用。
下面是 List 类现在的样子:
class List
{
// VARIABLES
private:
State* list[];
public:
int length;
// CONSTRUCTOR
List()
{
length = 0;
}
// Add elements to list
void add(State* s)
{
list[length] = s;
cout<<length<<" "<<list[length]<<endl; // Print the recently added element
length++;
}
// Print all the elements in the array
void show()
{
cout<<endl;
for (int i = 0; i < length; i++)
{
cout<<list[i]<<endl;
}
}
}
这是我在 main 函数中的代码:
int main()
{
// Initialize States
State s1 = State();
State s2 = State();
State s3 = State();
// Initialize List
List open = List();
// Print Original Addresses of States
cout<<&s1<<endl;
cout<<&s2<<endl;
cout<<&s3<<endl;
// Add Addresses to List
cout<<endl;
open.add(&s1);
open.add(&s2);
open.add(&s3);
// Loop over list to print addresses
open.show();
return 0;
}
这是输出:
0x70fad0
0x70fbe0
0x70fcf0
Element added at index 0 : 0x70fad0
Element added at index 1 : 0x70fbe0
Element added at index 2 : 0x70fcf0
0x30070fad0
0x70fbe0
0x70fcf0
State 对象的地址和添加到列表中的地址都是一样的,但是当遍历列表显示地址时,第一个地址是0x30070fad0 而不是0x70fad0,其余的都可以!
我不知道为什么会这样。
【问题讨论】:
-
State* list[];不是有效的 C++ -
即使该声明有效,C++ 也没有动态数组。如果你想要一个动态数组,你需要
std::vector。 -
更清楚一点...您没有为
State*分配任何空间。使用:State **list; ... list = new State*[max_num_objects]; -
再次,使用
std::vector。 -
@AhmedMustafa 要创建动态数组,请使用指针和
new[],要创建动态指针数组,请使用指向指针的指针,例如State** list; list = new State*[size];