C++ 类数据成员不可访问
我一辈子都搞不清楚这件事C++ 类数据成员不可访问,c++,visual-studio-2010,class,compiler-errors,syntax-error,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
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;
}
int-Warrior::攻击()
{
整数命中;
srand(时间(0));
如果(战士武器==6)
int hit=rand()%5+1;
else if(战士武器==7)
int hit=rand()%7+4;
else if(战士武器==8)
int hit=rand()%7+9;
否则如果(战士武器==9)
int hit=rand()%7+14;
否则如果(战士武器==10)
int hit=rand()%7+19;
std::coutWarrior
是类的名称。如果您在成员函数中,则不需要使用类的名称限定数据成员。您还应在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;
您最好使用开关
语句,甚至是%
和+
值的成对数组
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];
在上面的数组中,当武器
为8时,模块[武器]
为7
,而添加[武器]
是9
,与您的if
语句中的数据相匹配。如果不查看您的类定义,这是不可能的,但是您可能想要这个->武器
,或者,正如@chris所说,如果它是静态的,战士::武器
。此外,您只需要种子一次,而不是每次命中。您正在声明命中
5次。您只需要一个赋值。删除这些行上的int
关键字。在程序执行期间,您应该只调用srand(time(0))
一次。非常感谢,是的,我将使用switch语句。