在C ++中声明if-else块中的变量 [英] Declaring a variable in an if-else block in C++
问题描述
我正在尝试在if-else块中声明一个变量,如下所示:
I'm trying to declare a variable in an if-else block as follows:
int main(int argc, char *argv[]) {
if (argv[3] == string("simple")) {
Player & player = *get_Simple();
} else if (argv[3] == string("counting")) {
Player & player = *get_Counting();
} else if (argv[3] == string("competitor")) {
Player & player = *get_Competitor();
}
// More code
}
但是,当我尝试编译时,我遇到以下错误:
But, I'm getting the following errors when I try to compile:
driver.cpp:38:错误:未使用的变量
'player'
driver.cpp:40:错误:
未使用的变量'player'
driver.cpp:42:错误:未使用的变量
'player'< br> driver.cpp:45:错误:
'玩家'未在此
范围内声明
driver.cpp:38: error: unused variable ‘player’
driver.cpp:40: error: unused variable ‘player’
driver.cpp:42: error: unused variable ‘player’
driver.cpp:45: error: ‘player’ was not declared in this scope
有什么想法吗?
推荐答案
你的问题是每个if / else if块的播放器超出范围。
Your problem is that player falls out of scope in each if / else if block.
您需要在所有if语句之上声明您的变量。
You need to declare your variable above all of the if statements.
但是你不能使用引用,因为你必须立即初始化引用。
But you can't use a reference for that because you must initialize a reference right away.
你可能想要这样的东西:
Instead you probably want something like this:
int main(int argc, char *argv[]) {
Player * pPlayer = NULL;
if (argv[3] == string("simple")) {
pPlayer = get_Simple();
} else if (argv[3] == string("counting")) {
pPlayer = get_Counting();
} else if (argv[3] == string("competitor")) {
pPlayer = get_Competitor();
}
//Then if you really want to...
Player &player = *pPlayer;
}
这篇关于在C ++中声明if-else块中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!