如何使用new运算符创建秒对象

时间:2017-12-08 01:32:05

标签: c++ qt

我试图用运算符 new 创建2个类对象,但是当我试图创建一个新对象时,它表示第二个没有声明,如果我将接口更改为其他东西,它也会给出错误。

void Game::start(){
    // clear the screen
    scene->clear();

    //player1 = new Player("Player 1");
    //player2 = new Player("Player 2");
    player = new Player("Player1");

    interface = new Interface();
    interface2 = new Interface();
    //Interface interface;
    interface->placeCombatColumn();
    //interface.placeCombatColumn();
    drawGUI();
    interface->placeCombat();

}

错误:

  • 播放器未在此范围内声明

  • 未在此范围内声明interface2

1 个答案:

答案 0 :(得分:1)

你应该有一个(可能的)私人会员

Player * player;
你班上的

,就像这样:

class Game {

public:
  void start();

private:
  Player * player;

};

这样,您可以从player类方法(所有这些方法,包括Game)中引用变量start()。同样适用于其他变量,例如interface

如果您需要一个变量作为方法的本地变量(即,您不需要在方法范围之外),您必须声明它,至少在赋值时它,在方法内:

void Game::start() {

    // clear the screen
    scene->clear();

    Player * player = new Player("Player1");

...
相关问题