2013-01-18 114 views
2

今天早些時候我偶然發現了這個「問題」。轉換操作員問題

我有這個類,它包含一個轉換運算符。喜歡的東西:

class myClass { 
public: 
    ... 

    operator anotherClass*() { return anotherClassPtr; } 

    ... 
} 

現在這一切運作良好..直到我做了這個愚蠢的錯誤:

void yetAnotherClass::foo(myClass* _p_class) 
{ 
    ... 

    anotherClass* lp_anotherClass = (anotherClass*)_p_class; 

    ... 
} 

而且我花了很長時間才明白,爲什麼lp_AnotherClass PTR設置爲無事-zero,但我確信_p_class中的anotherClassPtr爲0.

有什麼我可以添加到myClass中,這會阻止我犯這個錯誤? (即編譯器會吐出一些錯誤)是否有可能阻止對象ptr被轉換爲其他東西?

回答

6
anotherClass* lp_anotherClass = (anotherClass*)_p_class; 

首先,你不應該使用C風格的演員。使用C++-style轉換。使用explicit轉換功能

auto* lp_anotherClass = static_cast<anotherClass*>(_p_class); //ERROR 

其次,喜歡:這將節省您的時間,因爲編譯器會告訴你馬上問題

explicit operator anotherClass*() { return anotherClassPtr; } 

爲什麼我建議explicit轉換功能,因爲它避免了微妙錯誤來自隱式轉換,此外,它增加了代碼的可讀性!

請注意,explicit轉換函數是一個C++ 11功能。

+0

感謝您的解釋。不幸的是,恰當命名的「myClass」實際上並不是我的...所以我不能將它改爲顯式操作符(我們還沒有切換到C++ 11)。 – Lieuwe

+0

@Lieuwe:很好。一旦你切換到C++ 11,開始採用更好的成語。暫時來說,你可以寫一些類似'to_anotherClass()'的東西。這個想法是一樣的:明確的! – Nawaz