我總是讀到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
C風格的演員陣容不一定與reinterpret_cast相同。在C++中,C風格強制轉換隻會等同於reinterpret_cast或const_cast(如果static_cast不行)。我希望我不要過分簡化事情,但我相信這是事情的要點。 – antred
*「我總是讀C++中的C風格類型與reinterpret_cast相同。」* - 要麼你沒有記錯,要麼你對閱讀材料的選擇特別不走運。 – IInspectable
傾向於使用C++強制轉換* always *。他們更明確地說出你想要做什麼*和*他們更容易在源代碼中搜索。當然,*最好的*是設計代碼,所以不需要(或者很少)演員。 –