开发者

Accessing and changing a class member function from another class

I have three classes I am trying to link together for my game. I am trying to make it so that if Player1 steps on a specific type of Tile then Player1's gravity variable "AccelY" will change providing the effect of a lift and raising the player up vertically. An initilisation class creates object Player1. (There is only one player so this can be applied to the whole class) This includes header files for CEntity.h a开发者_如何学运维nd CPlayer.h via CApp.h the main controller class. The CPlayer class is a child class of CEntity. Accel Y is declared publicly in CEntity as a float with no initial value. I want to change it in CPlayer when the player is on that type of tile. I have put an if statement clause in the Tile.h file but i cannot access and update the value using the following code? I initially tried by using the default class constructor but have tried with a function as below.

CTILE.CPP

#include "CTile.h"
#include "CPlayer.h"

CTile::CTile(){

    TileID = 0;

    TypeID = TILE_TYPE_NONE;

    if(TypeID == TILE_TYPE_LIFT){   

        CPlayer::LiftTile(0.75f, 10.0f);
        //CPlayer::AccelY = 0.75f;
        //CPlayer.SpeedY = 2.0; 
    }
}

CPLAYER.H

public:

    CPlayer();

    void LiftTile(float x, float y);

CPLAYER.CPP

void CPlayer::LiftTile(float x, float y){

    SpeedY = x;
    AccelY = y;
}


You would need a object of a class to access its members or call its member functions, unless the members or the member functions are declared static in that class.

CPlayer::LiftTile(0.75f, 10.0f);

can only work if CPlayer::LiftTile() is declared as

static void CPlayer::LiftTile(float x, float y); in `CPlayer` class

Other way is to call LiftTitle() by creating an object of CPlayer class, you would have to do something like this:

CTile::CTile()
{
    TileID = 0;

    TypeID = TILE_TYPE_NONE;

    if(TypeID == TILE_TYPE_LIFT)
    {   
        CPlayer obj;
        obj.LiftTile(0.75f, 10.0f);
        //obj.AccelY = 0.75f;  //works if AccelY is declared as public member
        //obj.SpeedY = 2.0;    //works if SpeedY is declared as public member
    }
}


If you want to access AccelY with class access specifier as, CPlayer::AccelY then the variable needs to be declared as static:

class CPlayer {
  static float AccelY;
};


It works if you use

Player1.LiftTile(0.75f, 10.0f);

As that calls the function for your specific player.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜