用define定义16种颜色常量要写16行代码,改成枚举类型后只要一两行就搞定:
#define cBlack 0 #define cNavy 1 #define cGreen 2 #define cTeal 3 #define cMaroon 4 #define cPurple 5 #define cOlive 6 #define cSliver 7 #define cGray 8 #define cBlue 9 #define cLime 10 #define cCyan 11 #define cRed 12 #define cMagenta 13 #define cYellow 14 #define cWhite 15
• enum cColor{ cBlack=0,cNavy,cGreen,cTeal,cMaroon,cPurple, cOlive, cSliver, • cGray, cBlue,cLime, cCyan,cRed, cMagenta,cYellow,cWhite };
之前写的《重载操作符<<实现cout定位输出以及设置颜色》,其代码就可以改进为:
#include <iostream> #include <windows.h> using namespace std; struct HannsC { DWORD fc; DWORD bg; }; struct HannXy { SHORT pX; SHORT pY; }; enum cColor{ cBlack=0,cNavy,cGreen,cTeal,cMaroon,cPurple, cOlive, cSliver, cGray, cBlue,cLime, cCyan,cRed, cMagenta,cYellow,cWhite }; HannsC setC(DWORD fc = 7, DWORD bg = 0) { fc %= 16, bg %= 16; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole,fc|bg<<4); return {fc, bg*16}; } HannXy Goto(SHORT x = 0, SHORT y = -1) { CONSOLE_SCREEN_BUFFER_INFO pBuffer; COORD position = {x, y}; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); if (position.Y==-1){ GetConsoleScreenBufferInfo(hConsole, &pBuffer); position.Y = pBuffer.dwCursorPosition.Y; } SetConsoleCursorPosition(hConsole, position); return {x, y}; } ostream& operator<<(ostream& _os, HannsC _mc) { return _os;} ostream& operator<<(ostream& _os, HannXy _xy) { return _os;} ostream& cr(ostream& _os) { _os.put('\n');_os.flush();return _os;} int main(void) { cout << setC(cNavy,cLime) << "abcdefghijklmnopqrstuvwxyz" << cr; cout << Goto(16,3) << setC(cYellow,cBlue) << "abcdefghijkl" << setC(cBlue,cYellow) << Goto(30) << 123 << cr << cr; cout << setC(cMagenta,cOlive) << 12312303236131230 << cr; cout << setC(cGreen,cWhite) << Goto(18,9) << "3.1415926535897932384626"; cout << Goto(30) << setC(cRed) << "END!" << Goto() << "cr && !lf"; cout << setC(cCyan) << cr << cr << "my C++ version: " << __cplusplus ; cout << setC() << cr; return 0; }
同时,也把原来放在 operator<<() 中的实现功能部分,移到setC()和Goto()函数中,这样更好理解可读性更好。