在类中访问结构对象变量- c++
Access Struct Object Variable within Class - C++
我会尽我所能解释清楚的。
基本上,我正在为GBA游戏编写这个程序,我正在尝试从类中更改结构实例的成员变量。下面是代码,省略了不必要的部分:
player.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);
}
}
player.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
无论我怎么尝试,我都无法越过这个错误。有人能给我解释一下吗?
它看起来不像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 );
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用