c++ - 用 reintepret_cast 解释对象地址

标签 c++ casting

以下代码给出的输出为 136。但我无法理解前两个地址比较是如何相等的。感谢任何有助于理解这一点的帮助。谢谢。

#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 d;
 A *b1 = &d;
 B *b2 = &d;

const int a = (reinterpret_cast<char *>(b1) == reinterpret_cast<char *>(&d)) ? 1 : 2;
const int b = (b2 == &d) ? 3 : 4;
const int c = (reinterpret_cast<char *>(b1) == reinterpret_cast<char *>(b2)) ? 5 : 6;

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

return 0;
}

最佳答案

当您像示例中那样使用多重继承时,第一个基类和派生类共享相同的基地址。您继承的其他类根据所有前面类的大小按偏移量顺序排列。比较结果为真,因为db1的基地址相同。

在您的情况下,如果 A 的大小为 4 个字节,则 B 将从 A + 4 个字节的基地址开始。当您执行 B *b2 = &d; 时,编译器会计算偏移量并相应地调整指针值。

当您执行 b2 == &d 时,在比较完成之前,会在 d 上执行从类型“C”到类型“B”的隐式转换。这种转换会像在赋值中一样调整指针值的偏移量。

关于c++ - 用 reintepret_cast 解释对象地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16763960/

相关文章:

c++ - 我在理解特定语法时遇到麻烦

java - Caused by : java. lang.ClassCastException : libcore. reflect.ParameterizedTypeImpl cannot be cast to java.lang.Class when use Generic Type 问题

在 F# 中与类型参数进行转换

c# - 要返回 double,即使类型在 c# 中是 double,我是否必须转换为 double?

c# - 字符串、对象和整数之间的转换和解析

c++ - 初始化const 3D数组成员变量

c++ - 为什么我的变量在我还没有设置它时返回一个值?

c++ - 如何使用 VSCode 调试 C++ 应用程序控制台应用程序?

c++ ptlib PNotifier 在 OPAL 中的使用

c# - 为什么在与 null 比较时转换为对象?