以下代码给出的输出为 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;
}
最佳答案
当您像示例中那样使用多重继承时,第一个基类和派生类共享相同的基地址。您继承的其他类根据所有前面类的大小按偏移量顺序排列。比较结果为真,因为d
和b1
的基地址相同。
在您的情况下,如果 A
的大小为 4 个字节,则 B
将从 A
+ 4 个字节的基地址开始。当您执行 B *b2 = &d;
时,编译器会计算偏移量并相应地调整指针值。
当您执行 b2 == &d
时,在比较完成之前,会在 d
上执行从类型“C”到类型“B”的隐式转换。这种转换会像在赋值中一样调整指针值的偏移量。
关于c++ - 用 reintepret_cast 解释对象地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16763960/