// Using if-else for this is inefficientvoidprintColor(Colorcolor){if(color==black)std::cout<<"black";elseif(color==red)std::cout<<"red";elseif(color==blue)std::cout<<"blue";elsestd::cout<<"???";}
#include<iostream>#include<string>enumColor{black,red,blue,};// We'll show a better version of this for C++17 belowstd::stringgetColor(Colorcolor){switch(color){caseblack:return"black";casered:return"red";caseblue:return"blue";default:return"???";}}intmain(){Colorshirt{blue};std::cout<<"Your shirt is "<<getColor(shirt)<<'\n';return0;}
#include<iostream>enumColor{black,red,blue,};// Teach operator<< how to print a Color// Consider this magic for now since we haven't explained any of the concepts it uses yet// std::ostream is the type of std::cout// The return type and parameter type are references (to prevent copies from being made)!std::ostream&operator<<(std::ostream&out,Colorcolor){switch(color){caseblack:out<<"black";break;casered:out<<"red";break;caseblue:out<<"blue";break;default:out<<"???";break;}returnout;}intmain(){Colorshirt{blue};std::cout<<"Your shirt is "<<shirt;// it works!return0;}
#include<iostream>enumPet:int// we've specified a base{cat,// assigned 0dog,// assigned 1pig,// assigned 2whale,// assigned 3};intmain(){Petpet{2};// ok: can initialize with integerpet=3;// compile error: can not assign with integerreturn0;}
无作用域枚举值的输入
由于 Pet 是一个程序定义类型,所以C++并不知道如何从std::cin输入一个 Pet:
1 2 3 4 5 6 7 8 91011121314151617
#include<iostream>enumPet{cat,// assigned 0dog,// assigned 1pig,// assigned 2whale,// assigned 3};intmain(){Petpet{pig};std::cin>>pet;// compile error, std::cin doesn't know how to input a Petreturn0;}
#include<iostream>enumPet{cat,// assigned 0dog,// assigned 1pig,// assigned 2whale,// assigned 3};intmain(){std::cout<<"Enter a pet (0=cat, 1=dog, 2=pig, 3=whale): ";intinput{};std::cin>>input;// input an integerPetpet{static_cast<Pet>(input)};// static_cast our integer to a Petreturn0;}
#include<iostream>enumPet{cat,// assigned 0dog,// assigned 1pig,// assigned 2whale,// assigned 3};// Consider this magic for now// We pass pet by reference so we can have the function modify its valuestd::istream&operator>>(std::istream&in,Pet&pet){intinput{};in>>input;// input an integerpet=static_cast<Pet>(input);returnin;}intmain(){std::cout<<"Enter a pet (0=cat, 1=dog, 2=pig, 3=whale): ";Petpet{};std::cin>>pet;// input our pet using std::cinstd::cout<<pet<<'\n';// prove that it workedreturn0;}