如何在其他类方法中引用类属性?
我正在尝试创建一个ASCII的小游戏,可以在其中绕过杀死敌人等。但是我是C ++的新手,如果玩家位置在某个点,我想做一些事情。
下面是代码的更简单版本,也是问题的图片:
#include <iostream>
using namespace std;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
void Setup()
{
}
int main()
{
Game game;
Player player;
while (!game.bGameOver)
{
Setup();
}
}
I'm trying to create a little ascii game where I can run around kill enemies etc. However I'm new to C++ and I would like to do something if the players location is at a certain point.
Below is a simpler version of the code and a picture of the problem:
#include <iostream>
using namespace std;
struct Game
{
bool bGameOver = false;
int iWidth = 20;
int iHeight = 40;
void Draw() {
if (player.x == 5)
{
cout << "Hello"
}
}
};
struct Player
{
bool bGameOver = false;
int x = 0;
int y = 0;
};
void Setup()
{
}
int main()
{
Game game;
Player player;
while (!game.bGameOver)
{
Setup();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
变量
player
在函数main
中是本地的,因此在尝试在game :: draw
中使用它的地方不可见。一种解决方案可能是使
player
成为全局变量。您需要切换结构的顺序:但是我更喜欢建模物品,以便
game
“具有”player
。因此,制作player
是game
的成员:(一边:您可能不需要两个不同的值称为
bgameover
,因为将它们保持在同步中将是额外的工作。The variable
player
is local in functionmain
, so it's not visible where you tried to use it inGame::Draw
.One solution could be to make
player
a global variable. You'll need to switch the order of the structs:But I'd prefer to instead model things so a
Game
"has a"Player
. So makePlayer
a member of theGame
:(Aside: You probably don't want two different values called
bGameOver
, since keeping them in sync would be extra work. It sounds more like a game property than a player property to me.)