#include <iostream>#include <string>enum Color{ black, red, blue,};// We'll show a better version of this for C++17 belowstd::string getColor(Color color){ switch (color) { case black: return "black"; case red: return "red"; case blue: return "blue"; default: return "???"; }}int main(){ Color shirt { blue }; std::cout << "Your shirt is " << getColor(shirt) << '\n'; return 0;}
#include <iostream>enum Color{ 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, Color color){ switch (color) { case black: out << "black"; break; case red: out << "red"; break; case blue: out << "blue"; break; default: out << "???"; break; } return out;}int main(){ Color shirt{ blue }; std::cout << "Your shirt is " << shirt; // it works! return 0;}
#include <iostream>enum Pet{ cat, // assigned 0 dog, // assigned 1 pig, // assigned 2 whale, // assigned 3};int main(){ Pet pet { 2 }; // compile error: integer value 2 won't implicitly convert to a Pet pet = 3; // compile error: integer value 3 won't implicitly convert to a Pet return 0;}
有两种方法可以解决这个问题。
首先,可以使用 static_cast 强制编译器将一个整数转换为无作用域枚举数:
#include <iostream>enum Pet{ cat, // assigned 0 dog, // assigned 1 pig, // assigned 2 whale, // assigned 3};int main(){ Pet pet { static_cast<Pet>(2) }; // convert integer 2 to a Pet pet = static_cast<Pet>(3); // our pig evolved into a whale! return 0;}
#include <iostream>enum Pet: int // we've specified a base{ cat, // assigned 0 dog, // assigned 1 pig, // assigned 2 whale, // assigned 3};int main(){ Pet pet { 2 }; // ok: can initialize with integer pet = 3; // compile error: can not assign with integer return 0;}
无作用域枚举值的输入
由于 Pet 是一个程序定义类型,所以C++并不知道如何从std::cin输入一个 Pet:
#include <iostream>enum Pet{ cat, // assigned 0 dog, // assigned 1 pig, // assigned 2 whale, // assigned 3};int main(){ Pet pet { pig }; std::cin >> pet; // compile error, std::cin doesn't know how to input a Pet return 0;}
#include <iostream>enum Pet{ cat, // assigned 0 dog, // assigned 1 pig, // assigned 2 whale, // 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){ int input{}; in >> input; // input an integer pet = static_cast<Pet>(input); return in;}int main(){ std::cout << "Enter a pet (0=cat, 1=dog, 2=pig, 3=whale): "; Pet pet{}; std::cin >> pet; // input our pet using std::cin std::cout << pet << '\n'; // prove that it worked return 0;}