2012-03-13 88 views
1

我想用一個靜態成員變量id_index來創建一個「Person」類來跟蹤下一個創建的類的ID(所以沒有兩個類有相同的ID)。當我運行該程序,我得到這些錯誤:創建一個ID靜態成員變量來跟蹤類ID

G:\WorkSpace\Human\Debug/../Person_Class/Person.cpp:11: multiple definition of `Person::id_index' 
Person_Class\Person_Set.o:G:\WorkSpace\Human\Debug/../Person_Class/Person_Set.cpp:10: first defined here 
Human.o: In function `main': 
G:\WorkSpace\Human\Debug/../Human.cpp:16: multiple definition of `Person::id_index' 
Person_Class\Person_Set.o:G:\WorkSpace\Human\Debug/../Person_Class/Person_Set.cpp:10: first defined here 

這是person.h文件:

#ifndef PERSON_H_ 
#define PERSON_H_ 
#include <iostream> 

class Person { 
public: 
    static unsigned int id_index; // will aut0-set to 0 
    Person(); 
}; 
unsigned int Person::id_index = 0; 
#endif /* PERSON_H_ */ 

的person.cpp:裏面存放的人類

Person::Person(): ID(id_index) { 

} 

主要功能。 cpp:

int main(){ 
    Person michael; 
    return 0; 
} 

回答

5

第二個person.h文件的最後一行, unsigned int Person::id_index = 0;屬於person.cpp。

同樣以功能定義中的.cpp屬於靜態變量定義(這是該行是什麼)怎麼也屬於中的.cpp。