通过函数引用传递一个对象并不能改变这个对象。

问题描述 投票:0回答:1

所以基本上,我想把一个对象传递给我的函数 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
c++ function pointers reference
1个回答
1
投票

在函数 onClick,变量 current 是通过值而不是引用传递的。我想这应该是通过引用传递的。

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

请注意这个参数 current 已更新为参考。

编辑。

看了看正文中的 Attack 函数,如果满足打印出名称的行,你确定if条件语句是 if(another.defensive > 0)if(attack > another.defensive) 是否满足?


0
投票

你认为 Position &positionx 可能是这里的问题?最重要的部分 onClick() 功能是 target = &positionx.positioning[i][j]. 但它是通过引用传递的,所以应该不会有问题。

© www.soinside.com 2019 - 2024. All rights reserved.