dimanche 19 avril 2015

Updating a Reference as a Class Member

I'm pretty sure I'm misunderstanding references.


In the code below, I'd like to initialize A to have a state, but at some time in the future, when I call init (registering a B object to A), I'd like stateB variable to show the value of the B state.


I can do this by making stateB a pointer, then initializing some memory in A's constructor and setting it to the default, then moving this pointer and deleting the memory when calling init.


Can I do this without stateB being a pointer by changing the reference of stateB to be b->state?



Class A {
public:
int stateB = 0;
B *b = nullptr;
void init(B *b) {
&state = &b->state;
}
}

class B {
public:
int state = 1;
}

Aucun commentaire:

Enregistrer un commentaire