私の意図はクラスAにBオブジェクトのリストを格納することですが、Bコンストラクターを呼び出すときにAリストに新しい要素を作成したいと思います。
私はこのようなコードを持っています:
class A
{...
protected:
std::list<B> Blist;
std::list<B>::iterator Bit;
...
public:
Update();
...
friend class B;
}
class B
{...
protected:
A* p_A;
...
public:
B(); //Standard constructor
B(A* pa); // This is the constructor I normally use
}
B::B(A* pa)
{
p_A=pa; // p_A Initialization
p_A->Bit = p_A->Blist.insert(p_A->Blist.end(), *this);
}
A::Update()
{
for(Bit=Blist.begin(); Bit != Blist.end(); Bit++)
{
(*Bit).Draw() //Unrelated code
}
}
void main() //For the sake of clarity
{
A* Aclass = new A;
B* Bclass = new B(A);
Aclass.Update(); // Here is where something goes wrong; current elements on the list are zeroed and data missed
}
プログラムは問題なくコンパイルされますが、プログラムを実行すると、目的の結果が得られません。
BIの場合、2つのコンストラクターがあります。デフォルトのコンストラクターはすべてをゼロにし、もう1つは入力を受け入れて内部変数を初期化します。
2番目を使用してプライベート変数を初期化すると、A.Updateメソッド中にすべてがゼロになり、代わりにデフォルトのコンストラクターを使用したように見えます。
私は何か間違ったことをしていますか?私のアプローチは正しいですか?
ありがとうございます!
編集:明確にするために編集されたプログラム