2016-04-03 103 views
0

所以我试图学习枚举类。我从我的书中复制了这段代码:Enum类只能用于-std = C++ 11

#include <iostream> 
using namespace std; 
int main() 
{ 
    enum class Color 
    { 
    RED, 
    BLUE 
    }; 

    Color color = Color::RED; 

    if (color == Color::RED) 
    cout << "The color is red!\n"; 
    else if (color == Color::BLUE) 
    cout << "The color is blue!\n"; 

    return 0; 
} 

我希望代码打印出“The Color is red!”。 然而,我的编译器会发出此错误:

warning: scoped enums only available with -std=c++11 or -std=gnu+11 

error:'Color' is not a class or namespace 

我目前使用开发 - C++ 5.11。任何想法如何解决这个问题?

+0

请在帮助中心阅读有关MCVE的信息。 – philipxy

+0

什么是“Dev-C++ 11”? –

+0

Dev-C++是一个免费的Windows IDE,它使用MinGW或TDM-GCC作为底层编译器。 –

回答

1

按照说明启用C++ 11支持。

  1. 导航到工具 - >编译器选项
  2. 设置标签
  3. 代码生成标签
  4. 变化Language standard -std到C++ 11
+0

另外,请考虑尝试使用Visual Studio等现代IDE。 ;) –

0

C++ 5.1枚举在同一范围内都必须例如:

enum Color1 { 
Bronze, 
Silver, 
Gold 
}; 

enum Color2 
{ 
Silver, //conflicts with Color1’s Silver 
Gold, //conflicts with Color1’s Gold 
}; 

C++ 11解决了一个所谓的新类别范围的enums.Keyword class范围界定问题的关键字枚举枚举名。您使用的是C++ 5.1 .Hence编辑代码如下之间出现:

#include <iostream> 
using namespace std; 
int main() 
{ 
    enum Color 
    { 
    RED, 
    BLUE 
    }; 

    Color color =RED; 

    if (color == RED) 
     cout << "The color is red!\n"; 
    else if (color == BLUE) 
     cout << "The color is blue!\n"; 
    return 0; 
} 

https://ideone.com/v42Ihs

1

枚举类是2011年添加到C++的枚举类型。因此,您必须对编译器说要使用该版本的C++(-std = C++ 11)。以前的C++版本,如C++ 03,没有这个功能。 Dev-C++在内部使用gcc作为编译器(g ++和gcc是同义词),并且Dev-C++版本使用的内部gcc版本可能是gcc 4.8.4甚至更早,在那个时候,“default “C++版本是C++ 03(03表示2003)。所以,你必须通知gcc你的源代码是用C++ 11用-std = C++ 11编写的。

gcc或任何其他编译器的现代版本默认假定您正在编译C++ 11代码(甚至是C++ 14代码),因此,您可以将该选项添加到旧编译器或更新您的IDE到默认使用C++ 11的版本。