【问题标题】:STL list and friend classes - Don't get desired outcomeSTL 列表和朋友类 - 不要得到想要的结果
【发布时间】: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-&gt;Bit 中只有一个 void/null 指针
  • 另外,你为什么用std::list&lt;B&gt;而不是std::list&lt;*B&gt;。 ?我感觉你根本不知道自己在做什么?
  • @DaanTimmer std::list&lt;B&gt; 有什么问题??
  • @mathematician1975 什么都没有。然而,如果A::update 方法不仅仅调用.Draw();,他将遇到问题,例如当B 对象更改他的内部值时。他目前只是将 B 对象复制到列表中。它还将使内存使用量等增加一倍。
  • 这里有潜在的递归问题 - 创建了一个 B 项目,告诉 A 添加一个 B 到它的列表,创建另一个 B,告诉 A 添加另一个……等等

标签: c++ list stl friend


【解决方案1】:

您可能想在取消引用之前尝试初始化您的 p_A。

【讨论】:

  • 初始化 p_A 不是问题 - 它在原始代码中作为参数传递。我将编辑以前的代码以使其更清晰
【解决方案2】:
std::list<B> Blist;

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

std::list<B*> Blist;

保留指针列表而不是对象将使A对象访问已经创建的B项目,而不是创建一个新的@987654329 @ 存在于列表中的对象。

【讨论】:

  • 这比我的更值得得到正确答案,因为代码已经修复并记录在其他地方设置了 p_A。 @tmpearce 关于 B 的估值与参考是正确的。通过在适当的地方定义适当的复制构造函数,并在不需要的地方删除默认构造,可以显着改善它,但这比其他任何东西都更精细。
【解决方案3】:

变化:

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);

应该可以解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    相关资源
    最近更新 更多