朋友功能我怎样才能在全球范围内改变他们的成员
Friend function how can i change their members globally
我如何才能全局更改友元函数的成员,而不仅仅是在其块内?我在下面有一个简单的例子:
预期输出(整数):
45
35
35
#include<iostream>
using namespace std;
class dog
{
private:
int HealthPoints;
int Damage;
public:
dog(int HealthPoints, int Damage){
this->HealthPoints = HealthPoints;
this->Damage = Damage;
}
friend void doAttack(dog,dog);
int getHealthPoints(){return HealthPoints;}
int getDamage(){return Damage;}
};
void doAttack(dog Attacker, dog Attacked){
Attacked.HealthPoints = Attacked.HealthPoints - Attacker.Damage;
cout << Attacked.HealthPoints << "\tvalue inside friend function" << endl;
}
int main()
{
dog a(45, 10);
dog b(45, 10);
cout << b.getHealthPoints() << "\tvalue before friend function" << endl;
doAttack(a, b);
cout << b.getHealthPoints() << "\tvalue after friend function";
return 0;
}
您不需要全局变量。您目前正在做的是按值传递 Attacker
和 Attacked
- 例如复制它们。您在 doAttack
中对这些副本进行了更改。原件永远不会被修改。而是通过引用传递它们。
我也更改了您的函数的名称,以便更友好。随时将其改回。
void doPet(dog& Petter, dog& Petted) {
Petted.LovePoints = Petted.LovePoints + Petter.Friendliness;
cout << Petted.LovePoints << "\tvalue inside friend function" << endl;
}
我如何才能全局更改友元函数的成员,而不仅仅是在其块内?我在下面有一个简单的例子:
预期输出(整数): 45 35 35
#include<iostream>
using namespace std;
class dog
{
private:
int HealthPoints;
int Damage;
public:
dog(int HealthPoints, int Damage){
this->HealthPoints = HealthPoints;
this->Damage = Damage;
}
friend void doAttack(dog,dog);
int getHealthPoints(){return HealthPoints;}
int getDamage(){return Damage;}
};
void doAttack(dog Attacker, dog Attacked){
Attacked.HealthPoints = Attacked.HealthPoints - Attacker.Damage;
cout << Attacked.HealthPoints << "\tvalue inside friend function" << endl;
}
int main()
{
dog a(45, 10);
dog b(45, 10);
cout << b.getHealthPoints() << "\tvalue before friend function" << endl;
doAttack(a, b);
cout << b.getHealthPoints() << "\tvalue after friend function";
return 0;
}
您不需要全局变量。您目前正在做的是按值传递 Attacker
和 Attacked
- 例如复制它们。您在 doAttack
中对这些副本进行了更改。原件永远不会被修改。而是通过引用传递它们。
我也更改了您的函数的名称,以便更友好。随时将其改回。
void doPet(dog& Petter, dog& Petted) {
Petted.LovePoints = Petted.LovePoints + Petter.Friendliness;
cout << Petted.LovePoints << "\tvalue inside friend function" << endl;
}