在下面的代码中,使用==比较两个对象显示的不同输出比比较两个字符指针。请帮我解决它的工作原理。
#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;
const int x = (pa == &c) ? 1 : 2;
const int y = (pb == &c) ? 3 : 4;
const int z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb)) ? 5 : 6;
std::cout << x << y << z << std::endl;
return 0;
}
输出: 136
为什么y的值为3,其中z的值为6.这里到底发生了什么 任何意见都表示赞赏。
答案 0 :(得分:4)
const int y = (pb == &c) ? 3 : 4;
相当于使用
B *pb2 = &c;
const int y = (pb == bp2) ? 3 : 4;
将&c
与B*
进行比较后,它会自动转换为B*
,从而抵消c
的地址以匹配B
部分C
。这就是表达式(pb == &c)
评估为true
的原因。
但是,pa
和pb
是不同的地址。因此,当您使用
(reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb))
该表达式的值为false
。
答案 1 :(得分:1)
You are using multiple inheritance. In this scenario, when you create an instance of Derived class typically what happens is :
Order in which the data of base classes in laid out in memory is the inheritance order you specify for Derived class. For your case:
class C: public A, public B
the memory layout of object looks like: A data members, B data members followed by C data members.
In your case pa and pb are actually pointing to different addresses but y is assigned a value 3 because of implicit conversion during comparison. But by doing reinterpret cast to a char* you are taking away the information that allows the compiler to do implicit casting. Instead a plain pointer comparison is done and the result is false.
If you do
C* pc = &c;
and check the value of pc in debugger, you will notice that it is the same as pa which highlights the above point.
答案 2 :(得分:0)
你传递了对象的地址&#39; c&#39;指针&#39; pa&#39; A级和A级指针&#39; pb&#39; B级。
As&#39; pa&#39; &安培;&安培; &#39; PB&#39;保持相同的内存参考对象&#39; c&#39; C类,因此表达变量x&amp;你是真的。
对于z变量的表达,你要比较&#39; pa&#39;的地址。用&#39; pb&#39;强制它们解释为强制转换指针,但这两个指针可能已分配在内存中的两个不同位置,因此它们不匹配,你得到z = 6(即假)