STL列表和朋友类 - 没有得到期望的结果
STL list and friend classes - Don't get desired outcome
我的意图是在类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);
应该能解决你的问题。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- valgrind-hellgrind与泄漏检查的结果不同
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- C++Brute Force攻击函数不会返回结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- STL列表和朋友类 - 没有得到期望的结果
- 不知道为什么结果会这样?我期望 15 50 5
- 绕过虚拟模板功能以实现期望的结果
- 为什么结果不在我的期望中
- 在c++中无法得到期望的结果
- CUDA中值滤波器的实现不能产生期望的结果