【发布时间】:2012-09-06 22:38:38
【问题描述】:
我的意图是在 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
}
好吧,程序编译没有问题,但是当我运行程序时,我没有得到想要的结果。
对于 B,我有两个构造函数,一个默认的将所有内容归零,另一个接受输入以初始化内部变量。
当我使用第二个初始化私有变量时,然后在 A.Update 方法期间,所有内容都归零,看起来我会使用默认构造函数。
我做错了吗?我的方法正确吗?
谢谢!
编辑:为清晰而编辑的程序
【问题讨论】:
-
你在哪里初始化/分配一个(新的)
A对象?目前,您在p_A->Bit中只有一个 void/null 指针 -
另外,你为什么用
std::list<B>而不是std::list<*B>。 ?我感觉你根本不知道自己在做什么? -
@DaanTimmer
std::list<B>有什么问题?? -
@mathematician1975 什么都没有。然而,如果
A::update方法不仅仅调用.Draw();,他将遇到问题,例如当B对象更改他的内部值时。他目前只是将 B 对象复制到列表中。它还将使内存使用量等增加一倍。 -
这里有潜在的递归问题 - 创建了一个
B项目,告诉A添加一个B到它的列表,创建另一个B,告诉A添加另一个……等等