映射引用同一个类

时间:2016-08-22 00:09:43

标签: c++ global-variables

我有一个类需要保留所有对象的引用列表。 例如:

//A.cpp
class A {
    A() {}
    someMethod() {}
    someOtherMethod() { mapA[0]->someMethod(); }
}

//main.cpp
#include <map>

std::map<int, A*> mapA;
int main(int argc, char const *argv[]) {
    int count = 0;
    A* a = new A();
    mapA[count] = a;
    count++;
}

但是,由于mapA只是main.cpp的全局,A.cpp无法引用它。我尝试使用extern,但由于map使用的是同一个类A,我不知道该把它放在哪里。

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以在构造函数中注册它们,并在类中创建静态var:

// a.hpp
class A {
public:
    A() { as.insert(this); }
    A(const A& rhs) { as.insert(this); }
    ~A() { as.erase(this); }
    static std::set<A*> as; // Declaration
};

// a.cpp
std::set<A*> A::as; // Definition