简体   繁体   English

结构给出不正确的输出

[英]Struct Giving Incorrect Output

When I compile this code, I get an output of 10 when it should be 0. 当我编译这段代码时,当它应该是0时,我得到10的输出。

#include <iostream>

struct player
{
    int hp;
    int dmg;
};

void dealdamage(player x, player y)
{
    y.hp = y.hp - x.dmg;
}

int main()
{
player p1, p2;
p1.hp = 10, p1.dmg = 10;
p2.hp = 10, p2.dmg = 10;
dealdamage(p1, p2);
std::cout << p2.hp << std::endl;
return 0;
}

Can anyone explain why? 有谁能解释为什么?

That's because you're passing the player structs in by value. 那是因为你按价值传递了player结构。

When the parameter is passed by value, a copy is made into the called function. 当参数按值传递时,将复制到被调用函数中。 So whatever changes you make in the function won't affect the original. 因此,您在函数中所做的任何更改都不会影响原始函数。

So your statement: 所以你的声明:

y.hp = y.hp - x.dmg;

Only affects the local copy of x and y . 仅影响xy的本地副本。 Which falls out of scope and is thrown away after the function ends. 超出范围并在功能结束后被丢弃。

The solution is to pass by reference like this: 解决方案是通过引用传递如下:

void dealdamage(player &x, player &y){

In this case, then changes made to x and y will be affect the originals. 在这种情况下,对xy所做的更改将影响原稿。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM