我想在Object中使用一个静态向量来存储指向所有构造的Object的指针,这样我就可以遍历每个Object。
//Object.h
public:
Object();
stuff();
static vector<Object*> objects;
//Object.cpp
vector<Object*> Object::objects;
Object::Object(){ objects.push_back(this); }
Object::stuff(){ /*Do stuff*/ }
我希望这项工作:
//ObjectB.cpp
Object::objects[0]->stuff();
当我运行它时,我收到“访问冲突读取位置0xCCCCCCCC”错误。
答案 0 :(得分:1)
Object.h:
#ifndef OBJECT_H
#define OBJECT_H
#include <vector>
using namespace std;
class Object {
public:
Object();
void stuff();
static vector<Object*> objects;
};
#endif // OBJECT_H
Object.cpp:
#include "Object.h"
#include <iostream>
using namespace std;
vector<Object*> Object::objects;
Object::Object() {
objects.push_back(this);
}
void Object::stuff() {
cout << "Stuff from object" << endl;
}
ObjectB.cpp:
#include "Object.h"
#include <vector>
using namespace std;
int main() {
Object a,b,c;
// this loop should run 3 times, as many as Object instance created
for (vector<Object*>::iterator it = Object::objects.begin(); it != Object::objects.end(); it++) {
(*it)->stuff();
}
return 0;
}
这就是你想要的吗?
答案 1 :(得分:1)
假设“ObjectB”类继承了“Object”类,那么Object.h和Object.cpp就可以了。
// Object.h
static vector<Object*> objects; // [Is this correct?][1]
- &GT;好的,静态成员声明
// Object.cpp
vector<Object*> Object::objects; // [Is this correct?][1]
- &GT;好的,静态成员初始化(在您的cpp文件中)
// Object.h
vector<Object*> Object::objects; //[error C2838][2]
- &GT;这是不对的,我假设ObjectB继承了Object,你不必声明它。要引用静态成员,只需执行“Object :: objects”即可。不要忘记从ObjectB构造函数中调用Object构造函数,否则您的ObjectB实例将不会添加到Object :: objects向量中:
// ObjectB.cpp
ObjectB() : Object() // Calling Object() will add your instance to "objects" vector
{
...
}
然后:
Object::objects.stuff(); // or with ->, i.e. Object::objects->stuff()
- &GT;这应该工作(如果你不忘记从ObjectB构造函数调用Object构造函数)。
问题是“还有另一种方法可以跟踪所有物体”,这取决于你想要实现的目标。