我无法为我的生活弄清楚这一点。
int Warrior :: attack ()
{
int hit;
srand(time(0));
if (Warrior.weapon == 6)
int hit = rand() % 5 + 1;
else if (Warrior.weapon == 7)
int hit = rand() % 7 + 4;
else if (Warrior.weapon == 8)
int hit = rand() % 7 + 9;
else if (Warrior.weapon == 9)
int hit = rand() % 7 + 14;
else if (Warrior.weapon == 10)
int hit = rand() % 7 + 19;
std::cout<< "You hit " << hit <<"!\n";
return hit;
}
我收到此错误:Error C2059: syntax error : '.'
(我也知道我应该使用switch
语句而不是else if
)
谢谢。
答案 0 :(得分:9)
Warrior
是该类的名称。如果您在成员函数内,则无需使用类的名称限定数据成员。您还应该在if-then-else:
hit
int hit;
if (weapon == 6)
hit = rand() % 5 + 1;
else if (weapon == 7)
hit = rand() % 7 + 4;
else if (weapon == 8)
hit = rand() % 7 + 9;
else if (weapon == 9)
hit = rand() % 7 + 14;
else if (weapon == 10)
hit = rand() % 7 + 19;
使用switch
语句,或者甚至是%
和+
值的一对数组,您可能会更好。
int mod[] = {0,0,0,0,0,0,5,7,7,7,7};
int add[] = {0,0,0,0,0,0,1,4,9,14,19};
int hit = rand() % mod[weapon] + add[weapon];
在上面的数组中,当weapon
为8时,mod[weapon]
为7
,add[weapon]
为9
,与数据匹配来自if
声明。