C++中單參數構造函數若不聲明為explict,在合適的場合可以產生隱式轉換:由成員變量類型轉換為類類型。
下面的代碼展示如何實現反向的轉換:?
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 void changeFontSize(FontHandle f, int newsize);
class Font{
public:operator FontHandle() const //隱式轉換函數{return f;}
private:FontHandle f;
};Font f;
int newsize;
changeFontSize(f, newsize); //將Font隱式轉換成FontHandle
另外,兩個或更多參數的non-explicit構造函數,如果所有形參都提供了默認實參,那么在需要一個類類型對象的表達式位置,提供一個first形參類型的對象,編譯器也執行隱式轉換,轉換得到一個類對象。