一、編譯時的錯誤捕捉 經典的隱式類型轉換問題: [cpp] #include "stdafx.h" class Apple { }; class Banana { }; class Orage { public: Orage(const Apple& apple); // Orage(const Apple& apple, const Banana *pBanana = 0); }; Orage::Orage(const Apple& apple){} Orage::Orage(const Apple& apple, const Banana *pBanana){} int _tmain(int argc, _TCHAR* argv[]) { Apple RedApple; Banana GreenBanana; Orage BlueOrage(RedApple); // Orage BlueOrage(RedApple, &GreenBanana); Orage BlueOrage = RedApple; return 0; } 這裡的問題出來了,可以讓一個Apple對象直接賦值給Orage對象,這是不正確的。為了防止這類隱式轉換的問題,加上修飾符即可 [cpp] #include "stdafx.h" class Apple { }; class Orage { public: explicit Orage(const Apple& apple); }; Orage::Orage(const Apple& apple){} int _tmain(int argc, _TCHAR* argv[]) { Apple RedApple; Orage BlueOrage(RedApple); Orage BlueOrage = RedApple; return 0; } 這樣在運行的時候,編譯器就會提示錯誤。 那麼如果真要使用=: [cpp] #include "stdafx.h" class Apple { public: operator Orage() const { Apple mine; Orage toConvertOrage(mine); return toConvertOrage; }; }; class Orage { public: explicit Orage(const Apple& apple); }; Orage::Orage(const Apple& apple){} int _tmain(int argc, _TCHAR* argv[]) { Apple RedApple; Orage BlueOrage(RedApple); Orage BlueOrage = RedApple; return 0; } 關於枚舉的: [cpp] #include "stdafx.h" enum { SUM, MON, TUE, WED, THU, FRI, SAT }; enum { JAN = 1, FEB, MAR, APR, MAY, JUN }; void IOnlyAcceptWeekType(int WeekType) { } int _tmain(int argc, _TCHAR* argv[]) { IOnlyAcceptWeekType(SUM); IOnlyAcceptWeekType(JAN); return 0; } 但是現在接受的卻不是我們想要的類型,所以不建議使用枚舉創建整型常量,而是用他們創建新類型: [cpp] #include "stdafx.h" typedef enum { SUM, MON, TUE, WED, THU, FRI, SAT } weekType; typedef enum { JAN = 1, FEB, MAR, APR, MAY, JUN } MonthType; void IOnlyAcceptWeekType(weekType WeekType) { } int _tmain(int argc, _TCHAR* argv[]) { IOnlyAcceptWeekType(SUM); IOnlyAcceptWeekType(JAN); // error return 0; }