STL列表和朋友类 - 没有得到期望的结果

STL list and friend classes - Don't get desired outcome

本文关键字:期望 结果 列表 朋友 STL      更新时间:2023-10-16

我的意图是在类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方法中,所有内容都为零,看起来我会使用默认构造函数。

我做错什么了吗?我的方法正确吗?

谢谢!

编辑:为清晰起见编辑的程序

在取消引用p_A之前,您可能需要尝试初始化它。

std::list<B> Blist;

这是一个类型为B的对象list。当您insert(iterator,value)时,您为列表提供了一个要复制的值。这将生成一个新的B对象,该对象将由复制构造函数创建的列表持有。如果B的复制ctor不执行所需的初始化步骤,则对象将不会处于所需的状态。

std::list<B*> Blist;

保留指针列表而不是对象将允许A对象访问已创建的B项,而不是创建位于列表中的新B对象。

更改:

std::list<B> Blist;
std::list<B>::iterator Bit;

std::list<B*> Blist;
std::list<B*>::iterator Bit;

p_A->Bit = p_A->Blist.insert(p_A->Blist.end(), *this);

p_A->Bit = p_A->Blist.insert(p_A->Blist.end(), this);

应该能解决你的问题。