2016-09-21 49 views
-7

我總是讀到C++中的C風格轉換與reinterpret_cast相同。但是,我只是在Visual Studio中測試了這段代碼,看起來C風格的轉型與靜態轉型執行的行爲相同。有人知道爲什麼嗎?這似乎是一個錯誤......在C++中使用C風格鑄造怪異行爲

#include <string> 
#include <iostream> 

class Thing1 
{ 
    std::string theString; 

public: 
    Thing1(const std::string& theString) : theString(theString) 
    { 
     // 
    } 

    std::string getTheString() 
    { 
     return theString; 
    } 
}; 

class Thing2 
{ 
    std::string theString; 

public: 
    Thing2(const std::string& theString) : theString(theString) 
    { 
     // 
    } 

    std::string getTheString() 
    { 
     return theString; 
    } 
}; 

class Thing3 : public Thing1, public Thing2 
{ 
public: 
    Thing3(const std::string& theString1, const std::string& theString2) : Thing1(theString1), Thing2(theString2) 
    { 
     // 
    } 
}; 

int main() 
{ 
    Thing3* thing3 = new Thing3("string1", "string2"); 
    uintptr_t t3ptr = (uintptr_t)thing3; 
    uintptr_t t1ptr = (uintptr_t)((Thing1*)thing3); 
    uintptr_t t2ptr = (uintptr_t)((Thing2*)thing3); 
    std::cout << t1ptr << std::endl; 
    std::cout << t2ptr << std::endl; 
    std::cout << t3ptr << std::endl; 
    std::cin.ignore(); 
    return 0; 
} 

這段代碼給出了輸出:

17563752 
17563780 
17563752 
+0

C風格的演員陣容不一定與reinterpret_cast相同。在C++中,C風格強制轉換隻會等同於reinterpret_cast或const_cast(如果static_cast不行)。我希望我不要過分簡化事情,但我相信這是事情的要點。 – antred

+6

*「我總是讀C++中的C風格類型與reinterpret_cast相同。」* - 要麼你沒有記錯,要麼你對閱讀材料的選擇特別不走運。 – IInspectable

+1

傾向於使用C++強制轉換* always *。他們更明確地說出你想要做什麼*和*他們更容易在源代碼中搜索。當然,*最好的*是設計代碼,所以不需要(或者很少)演員。 –

回答

7

C風格的轉換是不一樣的reinterpret_cast。

鑄造的概要可以在這裏找到: http://en.cppreference.com/w/cpp/language/explicit_cast

以下順序:

一個)的const_cast(表達); b)static_cast(表達式),帶有擴展:對派生類的指針或引用還允許被轉換爲指針或引用明確的基類(反之亦然),即使基類不可訪問(即,此轉換忽略私有繼承說明符)。同樣適用於將指向成員的指針指向非明確的非虛擬基的成員;

c)static_cast(帶擴展名)後跟const_cast;

d)reinterpret_cast(expression);

e)reinterpret_cast後跟const_cast。

+0

誰決定了這種行爲? dumb as hell – Finke

+2

@Finke:很明顯,這個命令是由標準委員會制定的。該命令在[cast.expr]第4節中列出。C還描述了類型轉換的強制轉換行爲。 – jxh

+6

@Finke:認爲編譯器有錯誤的人是因爲他們無法閱讀任何文檔。這種行爲總比'reinterpret_cast'ing好得多,並且更接近於C的工作方式。像'(int)5.5'這樣的東西如果C風格演員只是'reinterpret_cast'的簡稱,並且假設'reinterpret_cast'只是根據需要按位進行類型化處理,那麼結果是表情在幾乎所有的時間都是毫無用處的。 – GManNickG