在类中访问结构对象变量 - C++
Posted
技术标签:
【中文标题】在类中访问结构对象变量 - C++【英文标题】:Access Struct Object Variable within Class - C++ 【发布时间】:2014-03-29 01:03:44 【问题描述】:我会尽力解释这一点......
基本上,我正在为 GBA 游戏编写此程序,并且我正在尝试从类中更改结构实例的成员变量。这是代码,省略了不必要的部分:
播放器.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player::player()
x = 16;
y = 16;
health = 5;
direction = LEFT;
dead = false;
player::~player()
// Omitted unrelated code
void player::ScrollScreen() // Line 99
if(x>((240/2)-8))
BACKGROUND_2.h_offset += x-((240/2)-8);
播放器.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gba.h"
#include "font.h"
#pragma once
class player
public:
player();
~player();
unsigned int x;
unsigned int y;
void ScrollScreen();
;
BgLayerSettings.cpp
#include "player.h" // Line 1
#include "BgLayerSettings"
BgLayerSettings::BgLayerSettings()
charblock = 0;
screenblock = BLANK;
v_offset = 0;
h_offset = 0;
BgLayerSettings::~BgLayerSettings()
BgLayerSettings.h
#include <stdint.h> // Line 1
#include <stdlib.h>
#include <string.h>
#include "gbs.h"
#include "font.h"
#pragma once
enum BACKGROUND bg0=0, bg1, bg2, bg3, bg4, bg5, bg6, bg7,
bg8, bg9, bg10, bg11, bg12, bg13, bg14, bg15,
bg16, bg17, bg18, bg19, bg20, bg21, bg22, bg23,
bg24, bg25, bg26, bg27, bg28, DUNGEON_1, DUNGEON_FLOOR, BLANK,
;
struct BgLayerSettings
public:
BgLayerSettings();
~BgLayerSettings();
unsigned int charblock;
BACKGROUND screenblock;
int v_offset;
int h_offset;
;
main.cpp
#include "player.h" // Line 1
#include "BgLayerSettings.h"
player Player;
BgLayerSettings BACKGROUND_0;
BgLayerSettings BACKGROUND_1;
BgLayerSettings BACKGROUND_2;
BgLayerSettings BACKGROUND_3;
// Omitted unrelated code
本质上,我正在尝试从player
类中更改对象BACKGROUND_2
的变量h_offset
。
当我尝试编译它时,我收到了这个错误:
player.cpp: In member function 'void player::ScrollScreen()':
player.cpp:101:3: error: 'BACKGROUND_2' was not declared in this scope
make: *** [player.o] Error 1
无论我尝试什么,我都无法克服这个错误。谁能帮我解释一下?
提前致谢。
【问题讨论】:
【参考方案1】:它看起来不像 Player.cpp,特别是这一行...
BACKGROUND_2.h_offset += x-((240/2)-8);
可以看到BACKGROUND_2的实例。如果您在 main.cpp 中实例化它,那么 Player.cpp 将无法在构建过程中看到它。您应该将要更改的任何背景作为参考传递给函数,并从 main.cpp 更改它。取而代之的是这样的......
void player::ScrollScreen( BgLayerSettings &bg ) // Line 99
if(x>((240/2)-8))
bg.h_offset += x-((240/2)-8);
你的 main.cpp 应该是这样的......
player1.ScrollScreen( BACKGROUND_2 );
【讨论】:
那么在这种情况下,player.h
中的原型将如何查找void ScrollScreen();
?
类似 void ScrollScreen(BgLayerSettings &b)
如果你不想为 BgLayerSettings 添加包含,你可以通过放置 class BgLayerSettings 来转发声明它;高于你的 Player 定义。
为此辛苦了几个小时,终于修好了!非常感谢:)
我自己也去过。以上是关于在类中访问结构对象变量 - C++的主要内容,如果未能解决你的问题,请参考以下文章