gpt4 book ai didi

c++ - 在 C++ 范围外调用对象

转载 作者:行者123 更新时间:2023-11-28 07:08:32 24 4
gpt4 key购买 nike

我正在制作一个简单的基于文本的 rouge 游戏。在我的代码中,我为“房间”创建了一个类,并在我的主文件中创建了一个名为“Dungeon”的房间实例。这个对象范围出现了问题。我已经在“initGame()”函数中创建了它,但是我无法在主游戏循环中访问它。

我会发布所有相关代码,谢谢!

房间.h

#include <string>
#include "ConsoleCommands.h"
using std::string;


class room
{
public:
room(void);
room(string name);
~room(void);

//This creates the cells and populates the map//
static const int cellsX = 15;
static const int cellsY = 10;

string NAME;
int map;

void writeMap();
};

主要.cpp

int main(void)
{
initGame();
cout << "WELCOME, " + Player.NAME + " ";
return 0;
};

void initGame(void)
{
initCells();
lifeForm Player(100, 100, 100, newGameMenu());
room Dungeon("Dungeon");
}

最佳答案

Dungeon 和 Player 在 initGame 返回时被破坏。从函数返回房间和/或玩家实例。

你可以使用像这样的游戏结构:

struct Game
{
Game() : Player(100, 100, 100, newGameMenu()), Dungeon("Dungeon")
{
}

lifeForm Player;
room Dungeon;
}

然后

int main(void)
{
Game g;
cout << "WELCOME, " + g.Player.NAME + " ";
return 0;
};

关于c++ - 在 C++ 范围外调用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21395625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com