从对象数组中访问成员函数

时间:2016-10-30 16:41:06

标签: c++

我正在尝试动态创建一个对象数组,然后使用数组中对象的成员函数。我尝试了几种组合,但在尝试调用数组中对象的显示成员时崩溃了我的程序。

Something * pSomethings[12] = { NULL }; //pointer to array of 12 Somethings

to load the array I use:
Something * pSomething; //create a temp pointer of Something
pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget
cout << pSomething->getSize(); //seeing if data member was set (shows correct)
cout << pSomething->getWeight(); //seeing if data member was set (shows correct)

when I try to invoke the following my program breaks:
Something::display(){
Something * pSomething; //create another local temp pointer
pSomething = psomethings[0];//assign temp pointer to initialized pSomthing above
cout << pSomething->getSize(); // <---- breaks if run in main. 
}

我是c ++和指针的新手,所以我可能会犯一个非常简单的错误,但我根本不明白为什么getSize()在第一个函数中正确显示但在display()中我创建了相同的一切(临时指针,分配给相同的索引等),我得到一个错误。

2 个答案:

答案 0 :(得分:4)

看看这里的评论:

pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget

最后一条评论不正确,因为您将new返回的值分配给pSomething而不是分配给pSomethings[0]

你应该写:

pSomethings[0] = new Widget(size, weight); //pSomthings[0] should be a new widget

现在代码评论是正确的。

答案 1 :(得分:0)

你以错误的顺序做事。

你也在考虑有关作业的一些倒退 - x = a读取&#34;指定给x&#34;而不是相反。

特别是在序列中

pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget

第一个赋值将数组的第一个元素赋给pSomething,第二个赋值对数组没有影响 - 它仍然是一个空指针。
指针没什么特别之处;该代码与

完全相同
int x;
int y = 2;
x = y;
x = 10;

,之后你会期望y2而不是10,对吗?

重新排列代码并使代码与您的评论相符会使其有效:

Something * pSomethings[12] = { NULL }; //pointer to array of 12 Somethings

pSomethings[0] = new Widget(size, weight);//pSomethings[0] should be a new widget
Something * pSomething; //create a temp pointer to Something
pSomething = pSomethings[0]; //assign first item in array to temp pointer