Saturday, May 9, 2009

C++ reference to object, passing to constructors?

Hi everyone, I'm using some code (see below)


and I want to save the reference "%26amp;AdminRef" so that other functions in my class can use it, how should I do this?


(Sorry if this is a nooby question, just starting out and playing with C++)

C++ reference to object, passing to constructors?
class Player {





//Variables


string Name;





int Level;


int TotalHealth;


int CurrentHealth;


int WeaponID;


int ArmorID;


GameManager *Admin;





Player::Player(GameManager *AdminRef) {


Admin = AdminRef;








}


//Functions


void Player::Attack(string Type) {


AdminRef-%26gt;Attack("Player", Type);





}


}





int main()


{


GameManager Admin;


MainPlayer Player(%26amp;Admin);





return 0;


}





Make sure you initialize Admin in main before you pass it in to Player().
Reply:I tend to use pointers rather than references, but this is what I'd do:





class {





// Allocate a pointer for general use


GameAdmin* m_AdminRef


...


Player::Player( GameAdmin *AdminRef )


{


m_AdminRef = AdminRef;


}





void Player::Attack(string Type) {


m_AdminRef-%26gt;Attack("Player", Type);





} // end of class





This might also work as a reference; I'm not that up on them.





Hope that helps.
Reply:Just declare the reference in the class, so along with all your int and stuff write a


GameManager %26amp;adminRef





And in your constructor change it to adminRef = AdminRef to make your class's copy of adminRef equal to whatever you put it through your constructor.





Then you can access adminRef like any other variable in your class.


No comments:

Post a Comment