簡體   English   中英

類數據成員無法訪問

[英]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]7add[weapon]9 ,匹配if語句中的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM