26 listopada 2013

[C++11] Enumeratory

Nowy standard pozwala na istnienie zakresu dla enumeratorów (scope enumeration). Nazwę takiego enumeratora trzeba poprzedzić słowem "class" lub "struct".
#include <iostream>
using namespace std;

enum class EnumType {
    one,
    two,
    three
};

int main() {
    EnumType e = EnumType::two;
    return 0;
}
Enum zawsze jest reprezentowany przez wewnętrzny typu (domyślnie dla enum-ów z zakresem jest to int). W nowym standardzie typ ten można także podać po dwukropku.
#include <iostream>
using namespace std;

enum Song : unsigned long long {
    raz,
    dwa,
    trzy
};

enum class Colors : unsigned long long {
    white,
    green,
    blue
};

int main() {
    Colors c = Colors::green;
    Song s = Song::dwa;
    return 0;
}
Dopuszczalne jest także tworzenie forward deklaracji dla enum-ów. Ponieważ nie ma domyślnego rozmiaru dla niezakresowych enum-ów każdy z nich musi określać typ, przez jaki jest reprezentowany. Dla zakresowych jest to prostsze, ponieważ domyślnym typem jest tam int.
//enum EnumType;      // ERROR - brakuje słówka class, lub typu
enum class EnumType;
enum class Colors : unsigned long long;
enum OldEnum : int;

Brak komentarzy:

Prześlij komentarz