地址,reinterpret_cast和多重继承

Ale*_*pus 9 c++ pointers multiple-inheritance reinterpret-cast

任何人都可以解释以下代码的行为吗?

  1. 为什么我们b = 3在第一种情况下,即是真b2 == &d的?
  2. 为什么在案例2中没问题?我打印了b2和的地址d,它们是不同的.
#include <iostream>

using namespace std;

class A
{
public:
    A() : m_i(0) { }

protected:
    int m_i;
};

class B
{
public:
    B() : m_d(0.0) { }

protected:
    double m_d;
};

class C
    : public A
    , public B
{
public:
    C() : m_c('a') { }

private:
    char m_c;
};

int main()
{
    C d;
    B *b2 = &d;

    cout << &d << endl;
    cout << b2 << endl;

    const int b = (b2 == &d) ? 3 : 4; ///Case1: b = 3;
    const int c = (reinterpret_cast<char*>(b2) == reinterpret_cast<char*>(&d)) ? 3 : 4; //Case 2:  c = 4;

    std::cout  << b << c << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

APr*_*mer 9

d是C类型的指针.当你将一个指向C的指针转换为指向B的指针时,它会被调整为指向C的B子对象(如果B不需要多个继承,则通常需要这样的ajustement, A和C都有一个继承A和B).因此,在分配和比较时,完成调整.

在另外两个时间,&d被转换为void*(隐式)或char*(带有reinterpret_cast)并且没有进行调整(您明确要求使用reinterpret_cast进行无调整,并且在转换时没有理由进行调整为了无效*,它只会使往返复杂化没有充分的理由,你再次得到类似的结果A)所以表示是不同的.

顺便说一句,如果你曾经使用过reinterpret_cast<B*>(&d),那么就不会再进行任何调整,但是将结果用作B*会很快导致问题.