错误将此指针作为参数传递给类构造函数

时间:2016-11-21 01:48:53

标签: c++

我有3个类1)GameStateManager 2)MenuState(从另一个名为GameState的类继承)3)GameState

我想将此指针作为参数传递给MenuState的构造函数。

我的目标是在MenuState中获取指向GameStateManager对象的指针以供将来使用。

我收到错误:

error C2061: syntax error: identifier 'GameStateManager'
error C2664: 'MenuState::MenuState(const MenuState &)': cannot convert argument 1 from 'GameStateManager' to 'const MenuState &'
note: Reason: cannot convert from 'GameStateManager' to 'const MenuState'

GameStateManager.h

#pragma once

#include <vector>
#include <SFML/Graphics.hpp>
#include "MenuState.h"

class GameStateManager {
public:
    static const int MENUSTATE = 0;
    static const int FIRSTLEVELSTATE = 1;

    GameStateManager();

    ~GameStateManager();
private:
    std::vector<GameState*> States;
    int currentState;
};

GameStateManager.cpp

GameStateManager::GameStateManager() {
    this->currentState = MENUSTATE;
    this->States.push_back(new MenuState(*this)); // Error Line. I Think!
}

MenuState.h

#pragma once
#include "GameState.h"
#include "GameStateManager.h"
class MenuState: public GameState{
public:
    MenuState(GameStateManager& gsm);
    ~MenuState();
};

MenuState.cpp

MenuState::MenuState(GameStateManager& gsm){ // Error Line. I Think!
}

GameState.h

#pragma once
#include <SFML/Graphics.hpp>
class GameState {
//Virtual methods are here in this code which are not important for this question
public:
    GameState() {}
    ~GameState() {}
};

Main.cpp的

#include <SFML/Graphics.hpp>
#include "GameStateManager.h"

int main(int argc, char** argv) {
    GameStateManager gsm;
}

1 个答案:

答案 0 :(得分:1)

由于GameStateManager.hMenuState.h

中的标题包含冲突

如果声明为指针或引用,则使用前向声明:

  1. MenuState::MenuState(class GameStateManager& gsm);
  2. std::vector<class MenuState*> States;
  3. 然后,将行#include "GameStateManager.h"放入MenuState.cpp并将行#include "MenuState.h"放入GameStateManager.h将减少错误。