fja*_*sze 2 c++ for-loop declaration
有一些我对for语句没有理解的东西,在下面的代码中请集中注意力??? 评论:
void user_interface::execute_a_command( const string& cmd, command cmd_table[] )
{
LOG("user_interface::execute_a_command(): Executing \"",cmd,"\"");
bool command_executed = false;
//Exist any operation for this command?
command* elem = &cmd_table[ 0 ]; //???
for( int i = 0 ; cmd_table[ i ].function != nullptr ; i++, elem = &cmd_table[ i ] )
{
if( cmd == elem->name )
{
//Call the function
(this->*(elem->function))();
command_executed = true;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
好吧,这段代码编译得很好,没有特别的警告.但是,如果我将'elem'的声明和初始化放在'for'语句中,如下所示:
for( int i = 0 , command* elem = &cmd_table[ 0 ] ; cmd_table[ i ].function != nullptr ; i++, elem = &cmd_table[ i ] )
Run Code Online (Sandbox Code Playgroud)
g ++ 4.7.2不会使用此错误编译此代码:
game.cpp:834:27:错误:在' 'token game.cpp:834:27:错误:预期';'之前的预期初始化程序 在' '令牌之前
我不明白为什么.有人可以帮我理解这里的问题吗?
谢谢
您不能在初始化程序中声明不同类型的变量.如果它们属于同一类型,它将起作用:
for (int ii = 0, jj = 1, kk = 2; ii < count; ++ii, --jj, kk += 15) {
// ...
Run Code Online (Sandbox Code Playgroud)
继续进一步,多个变量声明要求它们具有相同的类型:
int a, b = 2, *c; // Yes
float x, double y, std::string z = "no"; // no
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |