无法初始化静态const字符串

时间:2014-03-05 14:27:26

标签: c++

我有一个“GameOverState”类,它有一个私有成员

static const std::string s_gameOverID;

在GameOverState.cpp中我初始化为:

const std::string GameOverState::s_gameOverID = "GAMEOVER";

我收到以下错误:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   
error C2440: 'initializing' : cannot convert from 'const char [9]' to 'int' 
error C2377: 'std::string' : redefinition; typedef cannot be overloaded with any other symbol
error C2373: 's_gameOverID' : redefinition; different type modifiers    
error C2143: syntax error : missing ';' before 'GameOverState::s_gameOverID'

我有一个PlayState类/ PauseState类,它具有相同的实现,工作正常。我该如何修复这个bug?

GameOverState.h

#pragma once

#include "GameState.h"
#include "PlayState.h"
#include "MenuState.h"
#include "PauseState.h"
#include "AnimatedGraphic.h"
#include <string>


class GameObject;

class GameOverState : public GameState
{
public:
  virtual void update();
  virtual void render();
  virtual bool onEnter();
  virtual bool onExit();
  virtual std::string getStateID() const { return s_gameOverID; }
private:
  static void s_gameOverToMain();
  static void s_restartPlay();
  static const std::string s_gameOverID;
  std::vector<GameObject*> m_gameObjects;
}

GameOverState.cpp        #include“GameOverState.h”

const std::string GameOverState::s_gameOverID = "GAMEOVER";

void GameOverState::s_gameOverToMain()
{
  TheGame::Instance()->getStateMachine()->changeState(new MenuState());
}

void GameOverState::s_restartPlay()
{
  TheGame::Instance()->getStateMachine()->changeState(new PlayState());
}

bool GameOverState::onEnter()
{
  if (!TheTextureManager::Instance()->load("assets/gameover.png", "gameovertext", TheGame::Instance()->getRenderer()))
  {
    return false;
  }
  if (!TheTextureManager::Instance()->load("assets/main.png", "mainbutton", TheGame::Instance()->getRenderer()))
  {
    return false;
  }
  if (!TheTextureManager::Instance()->load("assets/restart.png", "restartbutton", TheGame::Instance()->getRenderer()))
  {
    return false;
  }
  GameObject* gameOverText = new AnimatedGraphic(new LoaderParams(200, 100, 190, 30, "gameovertext"), 2);
  GameObject* button1 = new MenuButton(new LoaderParams(200, 200, 200, 80, "mainbutton"), s_gameOverToMain);
  GameObject* button2 = new MenuButton(new LoaderParams(200, 300, 200, 80, "restartbutton"), s_restartPlay);
  m_gameObjects.push_back(gameOverText);
  m_gameObjects.push_back(button1);
  m_gameObjects.push_back(button2);
  std::cout << "entering PauseState\n";
  return true;
}

2 个答案:

答案 0 :(得分:1)

GameOverState定义后,您错过了分号。

预编译器在编译之前运行,基本上只是复制粘贴源文件中标题的内容,尽管我们无法看到。因此,标题损坏导致的错误可能会产生误导。

在变量定义中包含类定义是合法的,并且说明符的位置(如static)也不限于声明的开头(例如,int const static x = 0;很好)。

因此,您的代码对编译器来说是这样的:

class GameOverState {} static const std::string GameOverState::s_gameOverID = "GAMEOVER";

希望错误现在更有意义。

答案 1 :(得分:0)

正如其他人所说的那样,如果你的其他两个类正常工作,你可能会错过标题中的#include行。它假定并期待一个int,所以情况似乎如此。

确保标题中有#include<string>