静态数据成员的问题-修复链接错误会导致编译器错误

Problem with static data member - fixing linking error creates a compiler error

本文关键字:错误 误会 编译器 链接 数据成员 问题 静态      更新时间:2023-10-16

game.h:

enum Game_state { MAIN_MENU, /*...*/ };
namespace list { class Linked_list { public: Linked_list() {} }; }
class Game {
public:
static Game_state state;
static list::Linked_list<Obj> objs;
};
Game_state Game::state = MAIN_MENU;
list::Linked_list<Obj> Game::objs = list::Linked_list<Obj>();

这给了我链接器错误:multiple definition of Game::state (and Game::objs)

如果我去掉类型说明符,它会给出编译器错误:'state' in 'class game' does not name a type (same for objs)

我所需要的只是初始化这些成员。

我在32位windows 10上使用mingw。

您必须将这些定义移动到一个转换单元(cpp文件(中。否则,每次在某个地方包含头文件时都会重新定义它们,从而违反ODR。

将"game::stat"answers"game:::objs"的定义放在*.cpp文件中并链接到它。