class MyLock
{
public:
explicit MyLock(Mutex *mutex) :m_mutexPtr(mutex, unlock)
{
lock(m_mutexPtr.get()); //lock函數需要Mutex的地址,可通過shared_ptr提供的顯示類型轉換函數get()
}
//~MyLock() {unlock(m_mutex);}
private:
std::tr1::shared_ptr<Mutex> m_mutexPtr;
};
class Product
{
public:
enum {CPU, KEY};
void SellProduct() {}
};
使用隱式類型轉換調用 std::tr1::shared_ptr<Product> ptr(GetProduct(1));
ptr->SellProduct(); //重載->獲得底層指針
(*ptr).SellProduct(); //重載*獲得底層對象</span>
RAII對象內的資源class FontHandls {};
void releaseFont(FontHandls * fh) {}
class Font
{
public:
explicit Font(FontHandls *fh) : m_fontHandls(fh) {}
~Font() {releaseFont(m_fontHandls);}
FontHandls *get() const {return m_fontHandls;}
private:
FontHandls *m_fontHandls;
};
隱式轉換接口,實現對應的重載操作符class FontHandls {};
typedef FontHandls* FontPtr;
void releaseFont(FontHandls * fh) {}
class Font
{
public:
explicit Font(FontHandls *fh) : m_fontHandls(fh) {}
~Font() {releaseFont(m_fontHandls);}
//FontHandls *get() const {return m_fontHandls;}
operator FontPtr (){return m_fontHandls;} //重載自定義類型,隱式轉換成內部指針
FontHandls *operator ->() const{ return m_fontHandls;} //隱式轉換
FontHandls operator *() const {return *m_fontHandls;} //隱式轉換
private:
FontHandls *m_fontHandls;
};
void OperateFont(FontHandls *fh) {};
調用 FontHandls *fh;
Font f(fh);
OperateFont(f);
對應RAII對象資源隱式轉換可能會出現的隱藏問題 FontHandls *fh;
Font f(fh);
FontHandls *fh2 = f; //願意是想拷貝Font對象,內部實際是轉換爲FontHandls*返回</span>
記住
②訪問可以通過顯式轉換或隱式轉換來實現。一般情況下,顯式轉換更安全,但是隱式轉換對於客戶端程序員來說使用更方便。