Visual C++:编译器错误C4430

Nic*_*ner 2 c++ syntax-error visual-c++

Game.h的代码:

#ifndef GAME_H
#define GAME_H

class Game
{
    public:
        const static string QUIT_GAME; // line 8
        virtual void playGame() = 0;
};

#endif
Run Code Online (Sandbox Code Playgroud)

错误:

game.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
game.h(8): error C2146: syntax error : missing ';' before identifier 'QUIT_GAME'
game.h(8): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

fbr*_*eto 8

你需要做两件事:

  • #include <string>
  • 将类型更改为const static std::string QUIT_GAME(添加std::)

  • 请注意,您无法在类声明中初始化字符串(甚至是常量静态字符串).在相应的源(.cpp)文件中必须有一个单独的定义语句(形式为`const std :: string Game :: QUIT_GAME ="Whatever";`).编辑:刚刚看到你的答案,下面详细解释了这一点,并对其进行了投票. (2认同)

Tho*_*ews 6

以下是解决问题所需的内容:

1.包含字符串头文件:
#include <string>

2.前缀string及其命名空间: const static std::string QUIT_GAME;

或插入一份using声明:

#include <string>
using std::string;
Run Code Online (Sandbox Code Playgroud)

3.为变量分配空间
因为您static在类中声明它,所以必须在代码中的某处定义它:
const std::string Game::QUIT_GAME;

4.用值初始化变量 因为你声明了字符串const,你需要将它初始化为一个值(或者它将保持一个常量空字符串):
const std::string Game::QUIT_GAME = "Do you want to quit?\n";

  • 不要在头文件中使用`using`.非常糟糕的juju.否则,伟大,全面的答案. (4认同)