C ++中的C风格转换给出了奇怪的行为

时间:2016-09-21 15:55:00

标签: c++ inheritance casting multiple-inheritance

我总是读到C ++中的C风格演员与reinterpret_cast相同。但是,我刚刚在Visual Studio中测试了这段代码,看起来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

1 个答案:

答案 0 :(得分:8)

C-Style强制转换与reinterpret_cast不同。

演员的摘要可以在这里找到: http://en.cppreference.com/w/cpp/language/explicit_cast

按以下顺序:

  

a)const_cast(表达式);

     

b)static_cast(expression),带有扩展:指向派生类的指针或引用另外允许转换为指针或引用明确的基类(反之亦然),即使基类是不可访问的(即,这个强制转换会忽略私有继承说明符)。同样适用于将指向成员的指针转换为指向非虚拟非虚拟基础成员的指针;

     

c)static_cast(带扩展名),后跟const_cast;

     

d)reinterpret_cast(表达);

     

e)reinterpret_cast,然后是const_cast。