我想知道在多重继承方面如何比较指针。在某些情况下,虽然地址明显不同,但它们似乎是平等的。请参阅以下代码:
class A {
int m_i;
};
class B {
double m_d;
};
class C: public A, public B {
char m_c;
};
int main() {
C c;
A *pa = &c;
B *pb = &c;
std::cout << "Address of c is: " << &c << std::endl;
std::cout << "A type pointer to c is: " << pa << std::endl;
std::cout << "B type pointer to c is: " << pb << std::endl;
std::cout << "if pa == &c: " << (pa == &c) << std::endl;
std::cout << "if pb == &c: " << (pb == &c) << std::endl;
return 0;
}
输出结果为:
c的地址是:00F6F870
指向c的类型指针是:00F6F870
B型指针c为:00F6F878
如果pa ==&amp; c:1
如果pb ==&amp; c:1
毫无疑问,pb与&amp; c不同。奇怪的是(pb ==&amp; c)提供1.我现在很困惑(pb ==&amp; c)实际上是如何评估的。
答案 0 :(得分:3)
您只能比较具有相同类型的值。请注意,出于此答案的目的,我忽略了重载operator==
的情况。
在这里,您要比较两个指向不同类的指针。此时,编译器会尝试确定是否可以将其中一个指针转换为另一个指针的类型。
指向子类的指针可以自动转换为指向其超类的指针。这就是编译器的作用。最终结果是相同的实际指针值,并且它们相等。
答案 1 :(得分:1)
这一行:
std::cout << "if pb == &c: " << (pb == &c) << std::endl;
为了将&c
与pb
进行比较,它必须执行转换,以便两个值的类型匹配。我们已经知道(B*)&c
会产生pb
中的值,所以这里实际发生的事情非常简单
std::cout << "if pb == &c: " << (pb == (B*)&c) << std::endl;
导致比较相等的值。
答案 2 :(得分:1)
class X {
char m_x;
};
class A {
int m_i;
};
class B {
double m_d;
};
class C: public X, public A, public B {
char m_c;
};
int main() {
C c;
A *pa = &c;
B *pb = &c;
void *va = pa;
void *vb = pb;
std::cout << "Address of c is: " << &c << std::endl;
std::cout << "A type pointer to c is: " << pa << std::endl;
std::cout << "B type pointer to c is: " << pb << std::endl;
std::cout << "void type pointer equal to pA is: " << va << std::endl;
std::cout << "void type pointer equal to pB is: " << vb << std::endl;
std::cout << "if pa == &c: " << (pa == &c) << std::endl;
std::cout << "if pb == &c: " << (pb == &c) << std::endl;
std::cout << "if va == &c: " << (&c == va) << std::endl;
std::cout << "if vb == &c: " << (&c == vb) << std::endl;
return 0;
}
产生以下结果:
Address of c is: 0x75270a47f5f0
A type pointer to c is: 0x75270a47f5f4
B type pointer to c is: 0x75270a47f5f8
void type pointer equal to pA is: 0x75270a47f5f4
void type pointer equal to pB is: 0x75270a47f5f8
if pa == &c: 1
if pb == &c: 1
if va == &c: 0
if vb == &c: 0
编译器将&amp; c地址转换为与您比较的指针相同的类型。为了明确这一点,我使用另一个类替换了A类,当我将地址复制到void *指针时,很明显实际的值是&#39;存储不等于&#39;值&#39;存储在&amp; c。
中