“多重定义”错误。我做错了什么?
我有以下类:
class Character
{
public:
Character();
Character(std::string char_name, Race char_race, Gender char_gender);
~Character();
int get_id() { return this->char_id; }
std::string get_name() { return this->name; }
Race get_race() { return this->race; }
Gender get_gender() { return this->gender; }
private:
int char_id;
static int * char_count;
std::string name;
Race race;
Gender gender;
};
int * Character::char_count = 0;
#endif // CHARACTER_H
请注意静态字段,它是在类外部初始化的。
这是实现:
Character::Character()
{
this->char_id = *char_count;
char_count++;
}
Character::Character(std::string char_name, Race char_race, Gender char_gender)
{
this->char_id = *char_count;
char_count++;
this->name = char_name;
this->race = char_race;
this->gender = char_gender;
}
Character::~Character()
{
}
显然我的编译器不喜欢这样。产生的错误是“Character::char_count 的多重定义”,但我没有看到多重定义。
???
I have the following class:
class Character
{
public:
Character();
Character(std::string char_name, Race char_race, Gender char_gender);
~Character();
int get_id() { return this->char_id; }
std::string get_name() { return this->name; }
Race get_race() { return this->race; }
Gender get_gender() { return this->gender; }
private:
int char_id;
static int * char_count;
std::string name;
Race race;
Gender gender;
};
int * Character::char_count = 0;
#endif // CHARACTER_H
Note the static field, which is initialized outside of the class.
Here's the implementation:
Character::Character()
{
this->char_id = *char_count;
char_count++;
}
Character::Character(std::string char_name, Race char_race, Gender char_gender)
{
this->char_id = *char_count;
char_count++;
this->name = char_name;
this->race = char_race;
this->gender = char_gender;
}
Character::~Character()
{
}
Apparently my compiler doesn't like this. The error produced is "multiple definition of Character::char_count", yet I see no multiple definition.
???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该静态字段的初始化
应位于 .cpp 文件中。否则会发生以下情况:一旦多个 .cpp 文件包含了 .h 文件,您就会获得静态字段的两个定义,这会导致稍后出现链接错误。包含防护在这里没有帮助 - 它们只能防止多次包含到同一个 .cpp 文件中,而不是包含到不同的 .cpp 文件中。
The initialization of that static field
should be in a .cpp file. Otherwise the following happens: once more than one .cpp file get the .h file included you've got two definitions of the static field and that cuases a link error later. The include guards won't help here - they only prevent multiple inclusion into the same .cpp file, not into different .cpp files.