任何人都可以解释重新解释转换如何在此代码中工作

Can anyone explain how reinterpret cast is working in this code

阅读以下正在使用的程序 reinterpret_cast.

#include <iostream>

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 c;
   A *pa = &c;
   B *pb = &c;

   bool z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb));
   std::cout << z;
   return 0;
}

在运行这个程序之后打印0,谁能解释一下 为什么 z 在这个程序中是假的??

Can anyone explain how reinterpret cast is working in this code

reinterpret_cast<char*>(pa) 求值为 char* 类型的指针,其数值与 pa 的数值相同。使用:

bool z = (pa == pb);

导致编译器错误,因为 AB 没有直接关系。使用

bool z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb));

允许您比较papb的数值。

After running this program it prints 0, can anyone explain why z is coming false in this program??

papb的数值不一样。因此,结果。您可以使用:

cout << "pa: " << std::hex << (void*)pa << std::endl;
cout << "pb: " << std::hex << (void*)pb << std::endl;

打印这些值并说服自己它们不相同。

如果你看一下 C 的内存布局,它看起来像:

+------+
|  m_i |     // The A sub-object
+------+
|  m_d |     // The B sub-object
+------+
|  m_c |     
+------+

当你使用

C c;
A* pa = &c;
B* pb = &c;

pa指向CA子对象,pb指向CB子对象.从图中可以看出,A子对象和B子对象之间有一个偏移量。因此,papb的数值是不同的。最有可能相差 sizeof(m_i)

reinterpret_cast 与此处的 static_cast 相同。 reinterpret_cast 发生在 运行 时,而 static_cast 发生在编译时。在这种情况下没有区别,但如果将强制转换应用于对象 c,就会有所不同。

A* pa = &reinterpret_cast<A&>(c); 
B* pb = &reinterpret_cast<B&>(c); 

将使 pa 和 pb 相同。虽然您有效地编写了 implicit 静态转换:

A* pa = &static_cast<A&>(c); 
B* pb = &static_cast<B&>(c);

并且由于这使得 pa 和 pb 不同,所以它们晚于 "reinterpreted" 并不重要。