2013-09-26 40 views
1

为什么下面的代码打印01
我预计00。为什么operator ==在第一种情况下返回true,如果地址不相等?C++多重继承,与派生对象中基类的地址混淆

#include <iostream> 

class B1 
{ 
    int m_i; 
}; 

class B2 
{ 
    double m_d; 
}; 

class D 
    : public B1 
    , public B2 
{ 
}; 

int main() 
{ 
    D d; 
    B2 *b2 = &d; 

    std::cout << "d:\t" << reinterpret_cast<void*>(&d) << "\t" << &d << "\n"; 
    std::cout << "b2:\t" << reinterpret_cast<void*>(b2) << "\t" << b2 << "\n"; 


    std::cout << (reinterpret_cast<void*>(b2) == reinterpret_cast<void*>(&d)); 
    std::cout << (b2 == &d); 

    return 0; 
} 

给出输出:

d: 0xbfd65fa4 0xbfd65fa4 
b2: 0xbfd65fa8 0xbfd65fa8 

01 
+0

(reinterpret_cast的(B2)==(d)的reinterpret_cast (&d));尝试。 –

+0

的std ::法院<< “(B2 *)&d \ t” 的<<的static_cast (d)<< “\ t” 的<<&d <<“\ n”; 是关键 – Michal

+0

好吧我知道了...... –

回答

3

当你比较b2&d没有铸造作废,编译器隐式影片投放到公共数据类型 - 在这种情况下,d被隐式现浇到其B2基类。

当你比较铸造作废,你得到的物体的真实基础地址,并自D继承B1B2之前这是其B1基类的地址。

+0

没错,谢谢。 – Michal