[英]Class Data Member Inaccessible
我不能為我的生活弄清楚這一點。
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
)
謝謝。
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
語句中的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.