2012-04-11 102 views
2

我在编译时出现此错误(G ++ 4.4.6):C++缺少初始化程序错误

main.cpp: In function ‘int main()’: 
main.cpp:27: error: expected initializer before ‘:’ token 
main.cpp:33: error: expected primary-expression before ‘for’ 
main.cpp:33: error: expected ‘;’ before ‘for’ 
main.cpp:33: error: expected primary-expression before ‘for’ 
main.cpp:33: error: expected ‘)’ before ‘for’ 
main.cpp:33: error: expected initializer before ‘:’ token 
main.cpp:36: error: could not convert ‘((list != 0u) ? (list->SortedList::~SortedList(), operator delete(((void*)list))) : 0)’ to ‘bool’ 
main.cpp:37: error: expected primary-expression before ‘return’ 
main.cpp:37: error: expected ‘)’ before ‘return’ 

我的代码如下:

#include <iostream> 
#include "Student.h" 
#include "SortedList.h" 

using namespace std; 

int main() { 
    SortedList *list = new SortedList(); 

    Student create[100]; 
    int num = 100000; 

    for (Student &x : create) { // <--Line 27 
     x = new Student(num); 
     num += 10; 
    } 

    for (Student &x : create) 
    list->insert(&x); 

    delete list; 
    return 0; 
} 

如果谁可能知道的源错误会有很大的帮助。另外,Student和SortedList是在.h文件中声明的对象。

+3

你用'-std = C++ 0x'编译吗? – ildjarn 2012-04-11 22:43:33

+0

我对C++有点新鲜,所以如果你能解释一下-std = C++ 0x是什么或者意味着非常感谢 – 2012-04-11 22:47:18

+1

@PatMurray:基于范围的for循环(你的第27行)是C++ 11的一个特性。您必须将'-std = C++ 0x'或(更新版本中的-std = c + 11)传递给编译器才能使用C++ 11功能。不过,我建议首先将您的编译器升级到新版本。 – 2012-04-11 22:49:18

回答

6

根据this page on GCC's website,基于范围的仅适用于g ++ 4.6及更高版本,因此您必须将代码转换为正常的for循环或使用std::for_each或其他东西,或升级编译器。

+0

好吧,这是有道理的。我修改我的代码,看看会发生什么 – 2012-04-11 22:49:38

+0

正常的for-loops编译正确。谢谢。 – 2012-04-11 22:54:54

+0

@PatMurray好,很高兴你得到它的工作。如果你接受这个答案,我将不胜感激,因为我距离今天的200只有5个声望,只剩下大约一个小时:) – 2012-04-11 22:58:52