gpt4 book ai didi

c++ - 通过引用将对象传递给函数不会更改此对象

转载 作者:行者123 更新时间:2023-12-02 10:17:30 25 4
gpt4 key购买 nike

所以基本上,我试图将对象传递给我的函数Attack():

void Character::Attack(Character &another, short int range)
{
if (EnemyInRange(range) && another.health > 0)
{
if (allowed_to_attack)
{
attacked = true;

cout << name << " attacked " << another.name << " taking " << attack << " damage" << endl;


if (another.defensive > 0) // less important things down there
{
another.defensive--;

if (attack > another.defensive)
{
another.health -= (attack - another.defensive);
}
}
else if (another.defensive == 0)
{
another.health -= attack;
}


if (another.defensive <= 0)
another.defensive = 0;

if (another.health <= 0)
{
another.health = 0;
another.draw = false;
another.~Character();
}

}

else
{
attacked = false;
cout << "Blocked" << endl;
}

}
else
cout << name << " wanted to attack " << another.name << " ,but he's out of the range" << endl;

如您所见,我正在使用引用传递对象。但是,当我调用此函数时:
void onClick(Vector2f mouse_position, Character current, Character *& target, Position &positionx)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
{
if ((mouse_position.x >= 245 + i * 164 && mouse_position.x <= 370 + i * 164) &&
(mouse_position.y >= 56 + j * 201 && mouse_position.y <= 221 + j * 201))
{ // there's a 2d map with cards on those positions
target = &positionx.positioning[i][j];
current.Attack(*target);
}
}
}

}

positioning is an array filled with characters



行为就像我传递了一个对象目标的副本(它写出名称,但不会改变其运行状况)

在main()中,它看起来像这样:
Character *current = new Character();
Character *target = NULL;
if ((event.type == Event::MouseButtonPressed) && (event.mouseButton.button == Mouse::Left))//SFML lib
{
Vector2i pos = Mouse::getPosition(window);
Vector2f position = (Vector2f)pos;
onClick(position, *current, target, positionx);
} // target is selected after clicking on it

最佳答案

onClick函数中,变量current通过值而不是引用传递。我假设应该通过引用传递:

void onClick(Vector2f mouse_position, Character &current, Character *target, Position &positionx)

请注意,参数 current已更新为引用。

编辑:

查看 Attack函数的主体,如果满足打印输出名称的行,您确定满足if-condition语句 if(another.defensive > 0)if(attack > another.defensive)吗?

关于c++ - 通过引用将对象传递给函数不会更改此对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61462424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com