【问题标题】:Creating an ID static member variable to keep track of class ID's创建一个 ID 静态成员变量来跟踪类 ID
【发布时间】:2012-03-13 01:00:24
【问题描述】:

我正在尝试使用静态成员变量 id_index 创建一个“Person”类,以跟踪创建的下一个类的 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) {

}

存储在human.cpp中的主函数:

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

【问题讨论】:

    标签: c++ main static-members


    【解决方案1】:

    person.h 文件的倒数第二行, unsigned int Person::id_index = 0; 属于 person.cpp。

    类似于函数definitions属于.cpp,静态变量definitions(也就是那行)也属于.cpp。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多