未定义的标识符
问题描述:
我正在学习C++并制作了一个脚本,一个攻击怪物类型的非常基本的玩家。但我得到未定义的标识符问题=/未定义的标识符
我不太明白为什么,我来自PHP背景,所以它可能并不完全适应C++严格的方式,但我希望有人能解释。
的错误:
main.cpp(30): error C2065: 'miss' : undeclared identifier
main.cpp(31): error C2065: 'hit' : undeclared identifier
main.cpp(43): error C2065: 'pmiss' : undeclared identifier
main.cpp(46): error C2065: 'phit' : undeclared identifier
main.cpp(47): error C2065: 'phit' : undeclared identifier
main.cpp(49): error C2065: 'mmiss' : undeclared identifier
main.cpp(52): error C2065: 'mhit' : undeclared identifier
main.cpp(53): error C2065: 'mhit' : undeclared identifier
我的脚本:
#include <iostream>
int player_health = 10;
int monster_health = 10;
void main(){
do{
std::cout << "#####################################" << std::endl;
std::cout<< "Pick you're weapon and hit enter!" << std::endl;
std::cout << "Press k for knife or b for Bat!" << std::endl;
std::cout <<""<<std::endl;
std::cout << "Player Health: "<< player_health << std::endl;
std::cout << "Monster Health: "<< monster_health << std::endl;
std::cout << "###################################"<< std::endl;
std::cout<<""<<std::endl;
char user_weapon;
std::cin >> user_weapon;
if(user_weapon == 'k' || user_weapon == 'b'){
if(user_weapon == 'k'){
int miss = 5;
int hit = 5;
} else if(user_weapon == 'b'){
int miss = 2;
int hit =3;
}
if((rand() % miss) < 3){
int phit = (rand()% hit);
} else {
bool pmiss = true;
}
//monster
if((rand() % 5) < 3){
int mhit = (rand()%3);
} else {
bool mmiss = true;
}
if(pmiss){
std::cout << "Player missed monster!"<<std::endl;
}else{
monster_health = monster_health - phit;
std::cout << "Player hit monster for " << phit << "!" << std::endl;
}
if(mmiss){
std::cout << "Monster missed player!"<<std::endl;
} else{
player_health = player_health - mhit;
std::cout << "Monster hit for " << mhit << "!" <<std::endl;
}
} else {
std::cout << "Invalid input , try either k or b" << std::endl;
}
}while(player_health >0 || monster_health > 0);
std::cout << "###################################"<< std::endl;
std::cout<<""<<std::endl;
if(player_health < 0 && monster_health < 0){
std::cout << "It's a draw!" << std::endl;
} else if (player_health > monster_health){
std::cout<<"Player Wins!" << std::endl;
} else {
std::cout<<"Monster Wins!" << std::endl;
}
std::cout << "###################################"<< std::endl;
std::cout<<""<<std::endl;
}
如果您运行脚本和我一样,你应该得到同样的错误。
答
if(user_weapon == 'k'){
int miss = 5;
int hit = 5;
} else if(user_weapon == 'b'){
int miss = 2;
int hit =3;
}
if((rand() % miss) < 3){
您正在定义miss
在if
的范围,然后在使用它的范围,所以:if((rand() % miss) < 3){
,你会得到miss
是不确定的 - 因为它仅被定义在你声明的范围它。
请注意,在C++中,你不能这样做,在C++中有静态作用域。
您应该在if
作用域之前定义miss
,并且仅在此处为其分配值。
当然,这同样适用于其他变量,如hit
和pmiss
。
无论何时出现错误,请复制并粘贴问题中的确切和完整的错误。没有它,我们不可能提供帮助。 – 2012-03-04 01:32:25
@SethCarnegie请参阅我的编辑:) – Sir 2012-03-04 01:35:29
在包含后添加'using namespace std;'。之后,你不需要再输入'std ::'。 – Blender 2012-03-04 01:36:32