由於各種無聊的原因,我需要一個盒裝的int類,它主要充當一個int,但是它是一個從基礎繼承的類,所以它可以與對象層次結構的其他部分一起工作。我包含了一個構造函數,它接受一個int類型以及一個int類型轉換,這樣我就可以輕鬆地將我的盒裝int與代碼中的常量int進行混合。但是,我看到一個非常奇怪的行爲,我無法弄清楚:當我從函數返回盒裝int時,我希望它使用我的拷貝構造函數來引用另一個BoxedInt。然而,它將我的盒裝int轉換爲int,然後使用我的int構造函數。這會導致問題,因爲在我的實際代碼庫中,在這種情況下,我想要複製其他基類屬性,並且通過使用此構造函數路徑來丟失它們。這是有問題的代碼:爲什麼C++選擇將我的返回值轉換爲int?
class BoxedInt
{
private:
int m_int;
public:
BoxedInt():m_int(0)
{
trace(L"Constructed with nothing");
}
BoxedInt(int val):m_int(val)
{
trace(L"Constructed with int");
}
BoxedInt(BoxedInt& val)
{
trace(L"Constructed with reference");
m_int = val.m_int;
}
operator int()
{
trace(L"Cast to int");
return m_int;
}
};
BoxedInt funky()
{
BoxedInt TempInt = 1;
return TempInt;
}
int main(int argc, char* argv[])
{
trace(L"Start");
BoxedInt test1 = 1;
trace(L"Copying");
BoxedInt test2 = test1;
trace(L"Assigning from return value");
BoxedInt test3 = funky();
trace(L"Done");
return 0;
}
當這個運行時,這裏的輸出:
Start
Constructed with int
Copying
Constructed with reference
Assigning from return value
Constructed with int
Constructed with reference
Cast to int
Constructed with int
Done
所以,當我分配一個值到另一個參考依據構造時,我會期望。但是,當我將函數的返回值賦給BoxedInt時,出於某種原因編譯器決定將其轉換爲int,然後使用int構造函數。我的C++很生疏,而且在編譯器這個奇怪的編譯器決策底部,我似乎無法抵消。有任何想法嗎?
閱讀關於顯式關鍵字http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean – fasked
編譯器不會**將返回值轉換爲' int',它**轉換**它。強制轉換是您在源代碼中編寫的內容,以告知編譯器進行轉換。同樣,'operator int'是一個**轉換操作符**,不是一個強制轉換。 –