变量未设置并返回异常数字

时间:2016-03-17 00:45:23

标签: c++ function class

我有一个用于计算对象造成的伤害的函数

string Weapon::attack(int Damage, int ExtraDamage, string Type)
{
    srand(time(NULL));

    int totalDamage = 0;

    int percentileDie = rand() % 100 + 1;

    if (percentileDie <= ChanceToHit) {

        for (int i = 0; i <= Damage; i++)
        {
            int sixSidedDie = rand() % 6 + 1;
            totalDamage = totalDamage + sixSidedDie;
        }
        totalDamage = totalDamage + ExtraDamage;
    }
    else {
        totalDamage = 0;
    }

    Result = totalDamage;

    if (Type == "Crossbow") {
        return "Twang! ";
    }
    else if (Type == "Dagger" || Type == "Sword") {
        return "Swing! ";
    }

}

但是,当我在程序中调用变量Result时,我得到了数字-858993460。我将Result = totalDamage更改为Result = 6以查看它是否会返回6,但它又一次返回-858993460

任何人都可以帮助我吗?

如果我这样做:

Weapon t;
t.attack(2, 4, "Sword");
cout << t.attack(2, 4, "Sword") << t.Result << endl;

我得到了正确的号码,但如果我这样做了:

Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;

我再次获得号码-858993460

此外,结果在类中声明:

class Weapon {
public:
    string Name;
    int Damage, ExtraDamage, Result;
    float ChanceToHit;

    string attack(int,int,string);
};

2 个答案:

答案 0 :(得分:4)

cout << X << YX未订购Y的评估顺序。

所以这段代码:

Weapon t;
cout << t.attack(2, 4, "Sword") << t.Result << endl;

将首先评估t.attack()t.Result - 根据您的帖子,似乎首先评估t.Result

解决方案是强制编译器以正确的顺序执行操作,例如

Weapon t;
std::string str = t.attack(2, 4, "Sword");
cout << str << t.Result << endl;

答案 1 :(得分:0)

如果你仔细研究这里到底发生了什么,那么你就会意识到运营商“&lt;&lt;”用于将数据添加到输出流。 “&lt;&lt;&lt;&lt;运营商被定义为在流上添加数据并返回修改流的引用以供进一步使用,这就是我们可以使用多个“&lt;&lt;&lt;”在单个“cout”中因此,将值放在流上的顺序与您读取它的顺序相反。

所以它就像

cout<<firstOperand<<secondOperand<<thirdOperand;

评估为

cout(<<firstOperand(<<secondOperand(<<thirdOperand)));

这反过来意味着首先将“thirdOperand”添加到输出流,然后返回更新的流。现在,“secondOperand”被推送到相同的返回流,然后“firstOperand”被推送到输出流。现在所有“&lt;&lt;”运营商已经完成。现在cout将流内容放在输出文件中。

因此,在您的情况下,因为在类函数中计算之前t.Result被添加到输出流中,所以您获得的值是在对象构造期间初始化的Result的随机值。

相关问题