类数据成员无法访问

kat*_*070 3 c++ compiler-errors class syntax-error visual-studio-2010

我不能为我的生活弄清楚这一点.

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;
}
Run Code Online (Sandbox Code Playgroud)

我得到这个错误:( Error C2059: syntax error : '.' 我也知道我应该使用一个switch语句而不是else if)

谢谢.

das*_*ght 9

Warrior是类的名称.如果您在成员函数内,则无需使用类的名称限定数据成员.你还应该hit在if-then-else链之前声明:

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;
Run Code Online (Sandbox Code Playgroud)

你可能会更好地使用一个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];
Run Code Online (Sandbox Code Playgroud)

在上面的数组中,当weapon是,例如,8,mod[weapon]is 7add[weapon]is 9,匹配来自if语句的数据.