假设我想装一袋蠕虫。我有class蠕虫,它有一个[[int属性ID。我也有一个课包:
class Bag{
// pointer to a 1D array of pointers to all the worms
Worm** population;
// constructor
Bag(){
// initiate 1D population of the worms
int N = 100;
Worm** population = new Worm*[N];
for (int i=0; i<N; i++){
Worm new_worm(i);
population[i] = &new_worm;
}
}
}
因为在编译时就知道N
,所以我不确定是否必须动态分配数组吗?我的问题是稍后在代码中我想执行:
Bag bag(); int ID = bag.population[10]->ID;
并且代码被编译,但是当我执行时得到Segmentation fault: 11
。我已经检查(通过评论)该问题是由ID提取的确切行引起的。我应该如何访问包中Worm类的字段和调用方法?
您正在分配局部变量“ population”,而不是成员“ population”-> bag.population仍为null