访问类中的结构对象变量 - C ++

时间:2014-03-29 01:03:45

标签: c++ class struct undefined member

我会尽力解释这个......

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

基本上我是在尝试从h_offset类中更改对象BACKGROUND_2的变量player

当我尝试编译时,我收到此错误:

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 个答案:

答案 0 :(得分: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 );