繁体   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