オブジェクトの配列を動的に作成し、配列内のオブジェクトのメンバー関数を使用しようとしています。私はいくつかの組み合わせを試しましたが、配列内のオブジェクトの表示メンバーを呼び出そうとするとプログラムがクラッシュします。オブジェクトの配列からのメンバー関数へのアクセス
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()は最初の関数ではなく、ディスプレイに正しく表示されるなぜ私は単に私が作成)(理解していませんすべて同じ(一時ポインタ、同じインデックスに割り当てるなど)、私はエラーが発生します。
pSomething = pSomethings[0]; //assign temp pointer to first item in array
pSomething = new Widget(size, weight);//pSomthings[0] should be a new widget
あなたはpSomething
へnew
から返された値を割り当てると最後のコメントが間違っている、ないpSomethings[0]
へ:
:
あなたのコードを再配置して、コメントコードの一致を作ることは、それが有効になるだろう。 –