c++中的C风格强制转换会产生奇怪的行为

C-Style casting in C++ giving weird behavior

本文关键字:中的 风格 转换 c++      更新时间:2023-10-16

我总是读到c++中的C风格强制转换与reinterpret_cast相同。然而,我刚刚在Visual Studio中测试了这段代码,似乎c风格的强制转换与静态强制转换执行相同的行为。有人知道为什么吗?这似乎是一个bug…

#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不同。

剧组的总结可以在这里找到:http://en.cppreference.com/w/cpp/language/explicit_cast

,顺序如下:

) const_cast(表达式);

b) static_cast(expression),带有扩展:派生类的指针或引用也可以被强制转换为无二义性基类的指针或引用(反之亦然),即使基类不可访问(也就是说,这种强制转换忽略私有继承说明符)。同样适用于将成员指针转换为明确的非虚基的成员指针;

c) static_cast(带扩展)后面跟着const_cast;

d) reinterpret_cast(表达式);

e) reinterpret_cast接const_cast.