c++ - 访问对象列表中的非常量成员

标签 c++ list stl constants

我想访问包含在此类对象列表中的对象的成员。

我有一个类CApp与成员(member)std::list<Particle> PList作为粒子列表。

A类Particle有成员(member)void Update()根据我对 const 的理解,它不能是 const,因为它会影响实例(欧拉积分和其他东西)。

我想遍历 PList 以更新所有粒子。

粒子构造函数包括:

Particle::Particle(std::list<Particle>* PList_In) {
    PList = PList_In;
    PList->push_back(*this);
}

多次调用以下内容:

Particle(&PList);

因此列表似乎已设置。作为旁注,如果此时有人可以解释内存(指针、引用)方面的实际情况,那就太好了。

但基本上这是错误的:

// Update all particles
std::list<Particle>::const_iterator iter;
for (iter = PList.begin(); iter != PList.end(); iter++) {
    iter->Update();
}

error: passing ‘const Particle’ as ‘this’ argument of ‘void Particle::Update()’ discards qualifiers

不知道该怎么办,如果需要更多信息/解释,请告诉我。

提前致谢!

最佳答案

使用 const_iterator 表示您不想更改列表元素。

如果你愿意,使用 std::list::iterator。

关于c++ - 访问对象列表中的非常量成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5387415/

相关文章:

c++ - QJsonDocument::toJson() 生成超大文本。有办法解决吗?

python - 如何将此字符串列表拆分为整数列表列表?

python - 如何从列表中删除除 Python 中的一个元素之外的所有重复项?

C++ 作为高级语言?

c++ - C++中 "Class instantiated object and variable inside the object address"的内存地址

c++ - 使Boost工作(Visual Studio 2010 Windows 2007)

c++ - 转义序列为 ?在 C++ 中

c - 多线程访问数据结构

c++ - 在所有节点作为结构 C++ 的排序列表中进行二进制搜索

c++ - 为索引寻找最接近的真实值