C++ 访问静态变量时未解析的外部符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8383330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:28:56  来源:igfitidea点击:

unresolved external symbol when accessing a static variable

c++linker-errors

提问by Ken Li

class CommandManager {

public:
    void sendText(std::string command);
    static bool CommandManager::started;

private:


    bool parseCommand(std::string commands);

    void changeSpeed(std::vector<std::string> vec);
    void help(std::vector<std::string> vec);
};

And here's the client code:

这是客户端代码:

CommandManager::started = true;

Linking these two files together I get:

将这两个文件链接在一起我得到:

1>UAlbertaBotModule.obj : error LNK2001: unresolved external symbol "public: static bool CommandManager::started" (?started@CommandManager@@2_NA)

1>C:\Development\School\cmput350-uofabot\UAlbertaBot\vs2008\Release\UAlbertaBot.dll : fatal error LNK1120: 1 unresolved externals

1> UAlbertaBotModule.obj : 错误 LNK2001: 未解析的外部符号 "public: static bool CommandManager::started" (?started@CommandManager@@2_NA)

1>C:\Development\School\cmput350-uofabot\UAlbertaBot\vs2008\Release\UAlbertaBot.dll:致命错误LNK1120:1个未解析的外部

Where did I go wrong here?

我这里哪里出错了?

回答by Nawaz

You're doing that incorrectly.

你这样做是错误的。

class CommandManager {

public:
    void sendText(std::string command);
    static bool started; //NOT this -> bool CommandManager::started
    //...
};

then put the definition of static member in .cppfile as:

然后将静态成员的定义放在.cpp文件中:

#include "CommandManager.h" //or whatever it is

bool CommandManager::started = true; //you must do this in .cpp file

Now you can useCommandManager::startedin your client code.

现在,您可以使用CommandManager::started在客户端的代码。

回答by Basile Starynkevitch

You should have inside your class:

你应该在你的班级里有:

class CommandManager {
 public:
  void sendText(std::string command);
  static bool started;
  //// etc
};

and outside your class, in a *.ccfile (not in a *.hhheader file), a definition like

在你的班级之外,在一个*.cc文件中(而不是在*.hh头文件中),一个像

bool CommandManager::started;

BTW, I believe you'll better make that private.

顺便说一句,我相信你会更好地做到这一点private

回答by Michael Krelin - hacker

Consider putting

考虑放

bool CommandManager::started;

where you defineother members.

在这里你定义的其他成员。