如何在类内部通过成员函数将多个类对象的数据存入同一ArrayList
实现类成员函数收集对象数据到共享列表
当然可以实现,你可以通过两种常见方式让类的成员函数把符合条件的对象数据存入同一个共享列表,先指出你原代码的核心问题,再给出修正后的方案:
原代码的核心问题
object构造函数中this->x;未完成赋值,应该改为this->x = x;arrList是类而非实例,直接调用arrList.store()会报错,非静态成员函数必须通过对象实例调用- 未处理动态分配的对象内存,会导致内存泄漏
方案一:使用类的静态成员变量作为共享容器
静态成员属于类本身,所有对象共享同一个实例,完美匹配“同一个列表”的需求。修改后的代码如下:
#include <vector> #include <cstdio> class object { public: int x; // 静态共享列表,所有object对象共用 static std::vector<int> sharedList; object(int x) { this->x = x; // 修正构造函数赋值问题 } void checkValue() { if (this->x > 5) { sharedList.push_back(this->x); } } }; // 静态成员必须在类外部初始化 std::vector<int> object::sharedList; int main() { object* objs[4]; for (int i = 0; i < 4; i++) { objs[i] = new object(i + 5); } for (int i = 0; i < 4; i++) { objs[i]->checkValue(); } // 验证结果:输出 6 7 8 for (int num : object::sharedList) { printf("%d ", num); } // 释放动态分配的内存,避免泄漏 for (int i = 0; i < 4; i++) { delete objs[i]; } }
方案二:让成员函数接收外部列表的引用
如果不想绑定静态成员(比如需要同时维护多个不同的共享列表),可以让checkValue函数接收外部列表的引用,灵活性更高:
#include <vector> #include <cstdio> class object { public: int x; object(int x) { this->x = x; // 修正构造函数赋值问题 } void checkValue(std::vector<int>& targetList) { if (this->x > 5) { targetList.push_back(this->x); } } }; int main() { std::vector<int> myList; // 外部定义的共享列表 object* objs[4]; for (int i = 0; i < 4; i++) { objs[i] = new object(i + 5); } for (int i = 0; i < 4; i++) { objs[i]->checkValue(myList); // 传入外部列表 } // 验证结果:输出 6 7 8 for (int num : myList) { printf("%d ", num); } // 释放动态分配的内存 for (int i = 0; i < 4; i++) { delete objs[i]; } }
额外注意事项
- 静态成员变量的生命周期和程序一致,需要清空时直接调用
object::sharedList.clear()即可 - 多线程环境下操作共享列表,必须加锁(比如
std::mutex)避免数据竞争 - 原代码中的
arrList类属于过度封装,直接用std::vector即可满足需求
内容的提问来源于stack exchange,提问作者crispYpickle
相关产品推荐
相关产品推荐

