PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : Change member of a class from another class



iciwi
27.08.2016, 10:25
Hey there,
I have a problem: I want to change the member of a class A from class B. So I made class B to a friend of class A. There is a function in class B that changes the variable "state". And in class A there is a function that checks if the variable "state" is 1. If true it will turn on an Led. I wrote this code:


class A {
friend class B;

private:
int state;
int Led = 13;
A(){
pinMode(Led, OUTPUT);
}

void update(){
if (state == 1){
digitalWrite (Led, HIGH);
}
}
};

class B{
public:
void update(){
state = 1;
}

};

A first;
B second;

void setup() {
// put your setup code here, to run once:

}

void loop() {
// put your main code here, to run repeatedly:
first.update();
second.update();
}


But it doesnt work. Where is the mistake? I hope somebody can help me.

Best regards

Maurice W.

Mxt
27.08.2016, 10:45
Hi,

the friend declaration does only say that B has access to A's private and protected elements.

But an instance of B does not know in which instance of A it should change the value of state. You could have something like this


A a, b, c;

there are three objects of type A, which one do you want to change ?

One possible solution would be giving B's update a parameter


class B{
public:
void update(A& a){
a.state = 1;
}

};

and using it this way


void loop() {
// put your main code here, to run repeatedly:
first.update();
second.update(first);
}


Much better C++ would be giving A a changeState method, instead of using friend.