I create a class, and in the class I declare a friend
function so that I can later change a private value with an if..else
statement, though I can't even change it without the if..else
.
#include <iostream>
using namespace std;
class A {
private:
float money;
friend void _setMoney(A a, float i);
public:
void setMoney(float i) {
money = i;
};
float getMoney() {
return money;
};
A(float i) {
i = money;
};
};
void _setMoney(A a, float i) {
a.setMoney(i);
};
int main(){
A a(0);
cout << a.getMoney() << endl;
a.setMoney(10);
cout << a.getMoney() << endl;
_setMoney(a, 20);
cout << a.getMoney() << endl;
}
After executing this in VS Code, I get 0, 10, 10
instead of 0, 10, 20
.
CodePudding user response:
The problem is not with _setMoney()
being a friend
or not. If that were the issue, your code would not even compile.
The real issue is that you are passing the a
object in main()
by value to _setmoney()
, so you are passing in a copy of the object, and are then modifying the copy rather than the original object.
Simply pass the object by reference instead:
void _setMoney(A& a, float i) {
a.setMoney(i);
};
That being said, A::setMoney()
is public
, so _setMoney()
does not need to be a friend
of A
in order to call it. Only if _setMoney()
wanted to access A::money
directly, eg:
void _setMoney(A& a, float i) {
a.setMoney(i); // <-- friend not required for this
a.money = i; // <-- friend required for this
};
CodePudding user response:
#include <iostream>
using namespace std;
class A {
private:
float money;
//////////////////////////////////////////////////////////
friend void _setMoney(A& a, float i);
//////////////////////////////////////////////////////////
public:
void setMoney(float i) {
//////////////////////////////////////////////////////////
money = i;
//////////////////////////////////////////////////////////
}
float getMoney() {
return money;
}
A(float i) {
money = i;
}
};
//////////////////////////////////////////////////////////
void _setMoney(A& a, float i) {
a.money = i; // friend privilege
}
//////////////////////////////////////////////////////////
int main(){
A a(0);
cout << a.getMoney() << endl;
a.setMoney(10);
cout << a.getMoney() << endl;
_setMoney(a, 20);
cout << a.getMoney() << endl;
return 0;
}