gpt4 book ai didi

c++ - 类数据成员不可访问

转载 作者:太空狗 更新时间:2023-10-29 19:59:34 25 4
gpt4 key购买 nike

我这辈子都想不通。

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]7,而 add[weapon]9,与 if 语句中的数据匹配。

关于c++ - 类数据成员不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12485425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com