类数据成员无法访问

时间:2012-09-18 21:34:45

标签: c++ visual-studio-2010 class compiler-errors syntax-error

我无法为我的生活弄清楚这一点。

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

谢谢。

1 个答案:

答案 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]7add[weapon]9,与数据匹配来自if声明。