>为什么在第一种情况下我们有b = 3,即b2 ==& d是真的?
>为什么在案例2中可以确定?我打印了b2和d的地址,它们是不同的.
#include <iostream>using namespace std;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; B *b2 = &d; cout << &d << endl; cout << b2 << endl; const int b = (b2 == &d) ? 3 : 4; ///Case1: b = 3; const int c = (reinterpret_cast<char*>(b2) == reinterpret_cast<char*>(&d)) ? 3 : 4; //Case 2: c = 4; std::cout << b << c << std::endl; return 0;}解决方法 d为C类型.当将指针C转换为B的指针时,将其调整为指向C的B子对象(如果不需要B,则需要这样的调整,通常需要多个继承,A和C之间的A将继承自A).因此,在分配和比较时间,进行调整.
在另外两个时间,& d被转换为voID *(隐含地)或者char *(有一个reinterpret_cast),并且没有调整完成(你明确地询问没有调整reinterpret_cast,没有理由做一个调整当转换为voID *时,只会使往返行程复杂化,没有什么好的理由,您再次对A有类似的结果,所以表示方式是不同的.
BTW,如果您已经使用了reinterpret_cast< B *>(& d),则不会再进行任何调整,但将结果作为B *使用会导致问题的快速发展.
总结以上是内存溢出为你收集整理的c – 地址,reinterpret_cast和多重继承全部内容,希望文章能够帮你解决c – 地址,reinterpret_cast和多重继承所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)