【发布时间】:2020-08-11 05:12:50
【问题描述】:
所以基本上,我正在尝试将一个对象传递给我的函数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);
}
}
}
}
定位是一个用字符填充的数组
它的行为就像我传递了一个对象目标的副本(它会写出名称,但不会改变它的健康状况)
在 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
【问题讨论】:
-
为什么要手动调用析构函数
another.~Character();,这个析构函数有什么作用?这可能会导致奇怪的行为,几乎没有理由手动调用析构函数。 -
我想确认一下,如果角色的生命值降到0,它就会被摧毁
标签: c++ function pointers reference