简体   繁体   English

类数据成员无法访问

[英]Class Data Member Inaccessible

I can't for the life of me figure this out. 我不能为我的生活弄清楚这一点。

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;
}

I get this error: Error C2059: syntax error : '.' 我收到此错误: Error C2059: syntax error : '.' (also I know I should use a switch statement instead of else if ) (我也知道我应该使用switch语句而不是else if

Thank You. 谢谢。

Warrior is the name of the class. Warrior是班级的名字。 If you are inside of a member function, you do not need to qualify data members with the name of the class. 如果您在成员函数内,则无需使用类的名称限定数据成员。 You should also declare hit before the chain of if-then-else: 你还应该在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;

You would probably be better off with a switch statement, or even an array of pairs for % and + values. 使用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];

In the arrays above, when weapon is, say, 8, the mod[weapon] is 7 , and the add[weapon] is 9 , matching the data from your if statement. 在上面的数组中,当weapon是8时, mod[weapon]7add[weapon]9 ,匹配if语句中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM