Unresolved External Symbol - 关于类的static变量



转自

http://hi.baidu.com/hypkb/item/b8e1db90998ae0de7a7f010f


Unresolved External Symbol - 关于类的static变量

转的

一个简单的程序,实现可以在类的静态Vector<Object*>保存该类的所有实例

    Object.H

1: # include <vector> 2: 3: #ifndef _OBJECT_H 4: #define _OBJECT_H _ 5: 6: using namespace std; 7: 8: class Object 9: { 10: public: 11: int data; 12: static vector<Object*> dataInstance; 13: Object(int num); 14: Object(); 15: }; 16: 17: #endif

     Object.Cpp

1: # include "object.h" 2: 3: Object::Object(int num) 4: { 5: data = num; 6: Object::dataInstance.push_back(this); 7: }

    编译没有语法错误,但是连接的时候出现LNK2001错误。

    原来对于类的static变量,需要在类外(也就是对应的.cpp中加入声明

    在Object.cpp中加入:

1: vector<Object*> Object::dataInstance;

就可以编译通过了

发布了146 篇原创文章 · 获赞 13 · 访问量 71万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章