顯示構造函數與轉換運算符的合作
在設計一個Date類的時候,我們使用int類型來表示年份,如果我們需要對年份進行一些特殊的操作(如:檢查,保護等),就很需要定義一個Year類,如下:
在這里Year就只是包裹住了int,對int提供一層保護而已。由于operator int()的存在,只要需要,Year可以隱式的轉化為int出現運算表達式中參加運算。而通過給構造函數聲明為explicit,就能夠保證,int到Year的轉化只能在明確無誤的情況進行,避免了意外的賦值。
顯示構造函數和轉換運算符的合作,讓Year可以當int使用,同時又對Year進行一定的保護。。。
class Year {
int m_y;
public:
//explicit限制int到Year的隱式轉換
explicit Year(int y)
: y(m_y) { }
//Year到int的類型轉換
operator int() const
{ return m_y; }
//other funtion
}
int m_y;
public:
//explicit限制int到Year的隱式轉換
explicit Year(int y)
: y(m_y) { }
//Year到int的類型轉換
operator int() const
{ return m_y; }
//other funtion

}
class Date {
public :
Date(int d, Month m, Year y);
//
};
Date d1(1987, feb, 21); //error, 21不能隱式轉換為Year
Date d2(21, feb, Year(1987)); //ok
public :
Date(int d, Month m, Year y);
//

};
Date d1(1987, feb, 21); //error, 21不能隱式轉換為Year
Date d2(21, feb, Year(1987)); //ok
在這里Year就只是包裹住了int,對int提供一層保護而已。由于operator int()的存在,只要需要,Year可以隱式的轉化為int出現運算表達式中參加運算。而通過給構造函數聲明為explicit,就能夠保證,int到Year的轉化只能在明確無誤的情況進行,避免了意外的賦值。
顯示構造函數和轉換運算符的合作,讓Year可以當int使用,同時又對Year進行一定的保護。。。
posted on 2009-08-13 14:39 Marcky 閱讀(275) 評論(0) 編輯 收藏 引用 所屬分類: C/C++