2010-05-26 150 views
2

Game.h的代码:的Visual C++:编译器错误C4430

#ifndef GAME_H 
#define GAME_H 

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

#endif 

错误:

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 

我在做什么错?

回答

6

以下是你需要修复您的问题是什么:

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

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

或插入using声明:

#include <string> 
using std::string; 

3.分配空间的变量
既然你宣布它作为类中static,它必须是在代码某处定义
const std::string Game::QUIT_GAME;

4.用变量初始化变量 既然你宣布与const字符串,你需要将其初始化为一个值(或它会保持一个恒定空字符串):
const std::string Game::QUIT_GAME = "Do you want to quit?\n";

+4

不要在头文件中使用''使用''。非常糟糕的juju。否则,很好,全面的答案。 – 2010-05-26 21:16:23

4
#include <string> 
... 
const static std::string QUIT_GAME; 
+6

你不应该把一个'using'声明在头文件。它不可逆转地污染了包含的任何文件的命名空间。 – 2010-05-26 20:54:34

+0

@Adam:固定~~~ – 2010-05-26 20:57:01

8

你需要做两件事情:

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

其实还有一件事:初始化变量。 'const'说明符在这里是踢球者。如果变量未初始化,它将是一个常量空字符串。这有用处,但我不认为这是OP想要的。 – 2010-05-26 21:02:21

+2

请注意,您不能在类声明中初始化一个字符串(即使是一个常量静态字符串)。在相应的源文件(.cpp)中必须有一个单独的定义语句(形式为const const std :: string Game :: QUIT_GAME =“Whatever”;')。编辑:刚才看到你的答案,这在下面详细解释,并upvoted它。 – 2010-05-26 21:14:08

2

缺少的#include<string>

,它的std::string

0

尝试添加在顶部:

#include <string> 
using std::string; 
+0

在标题??谁投了票? – sbi 2010-05-26 22:08:48