2012-09-18 41 views
3

我不能为我的生活弄清楚这一点。级别数据会员无法访问

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 : '.' (也是我知道我应该使用,而不是一个else if声明switch

谢谢。

+3

没有看到你的类定义是不可能的,但你可能需要'this-> weapon',或者像@chris所说的那样,如果它是静态的,'Warrior :: weapon'。 – slugonamission

+1

另外,你只需要一次种子,而不是每次击中。 – slugonamission

+2

你重新声明了5次“命中”。你只是想要一个任务。删除这些行上的'int'关键字。你应该在程序执行期间只调用'srand(time(0))'一次*。 –

回答

9

Warrior是该类的名称。如果您在成员函数内部,则不需要使用该类的名称来限定数据成员。

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语句,甚至是对%+值对数组更好:你也应该的IF-THEN-ELSE链之前宣布hit

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声明相匹配的数据。

+0

非常感谢,而且我会用switch语句代替。 – katana7070