0

我想要一些数据缓存,其中包含一些我可以通过UpdateCache函数更新的对象。但是,我遇到了 aLNK2001后跟 a 的问题LNK1120

HeaderFile.h

#ifndef headerfile_included
#define headerfile_included
#include <vector>
struct MyObject {
    unsigned int A;
    unsigned int B;
};
class MyClass {
private:
    static std::vector<MyObject> myObjectCache;
public:
    static void UpdateCache ();
};
#endif

CodeFile.cpp

#include "HeaderFile.h"
void MyClass::UpdateCache () {
    myObjectCache.clear();
    /* Repopulate cache with new data */
}

我从链接中得到的错误信息是

错误 LNK2001: 无法解析的外部符号 ""private: static class std::vector > MyClass::myObjectCache" (?myObjectCache@MyClass@@0V?$vector@UMyObject@@V?$allocator@UMyObject@@@std@@@标准@@A)"。

致命错误 LNK1120:1 个未解决的外部问题

我的观点是分区到头文件和代码文件有一些问题,因为我在分区不正确时遇到了类似的问题。如果再次出现这样的问题,那么如果您可以发布一些关于将什么放入头文件以及将什么放入代码文件的规则会很好,因为它非常令人困惑。

4

2 回答 2

7

您需要将其添加到 cpp 文件中:

std::vector<MyObject> MyClass::myObjectCache;

原因是由于静态存在而没有实例化类,因此无论类的实例是否实例化,它都需要存在。上面的行创建了 static 的实例,因此无论您是否创建了类本身的实例,它都存在。

于 2009-10-22T20:01:42.500 回答
3

Since your vector is static, essentially a global entity as far as the compiler is concerned, you need to be sure to give it a home in a compilation unit. That's why you have to do what @Goz says and do

std::vector<MyObject> MyClass::myObjectCache;
于 2009-10-22T20:03:18.660 回答