在类中访问结构对象变量- c++

Access Struct Object Variable within Class - C++

本文关键字:变量 c++ 对象 结构 访问      更新时间:2023-10-16

我会尽我所能解释清楚的。

基本上,我正在为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 );