“多重定义”错误。我做错了什么?

发布于 2024-11-30 21:02:28 字数 1039 浏览 2 评论 0原文

我有以下类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迟到的我 2024-12-07 21:02:28

该静态字段的初始化

int * Character::char_count = 0;

应位于 .cpp 文件中。否则会发生以下情况:一旦多个 .cpp 文件包含了 .h 文件,您就会获得静态字段的两个定义,这会导致稍后出现链接错误。包含防护在这里没有帮助 - 它们只能防止多次包含到同一个 .cpp 文件中,而不是包含到不同的 .cpp 文件中。

The initialization of that static field

int * Character::char_count = 0;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文