对象的地址问题C/C++ code#includeiostream#includealgorithmusing namespace stdclass T0{public:vi
对象的地址问题
- C/C++ code
#include<iostream>#include<algorithm>using namespace std;class T0{public: virtual ~T0() {}};class T1{public: virtual ~T1() {}};class T2{public: virtual ~T2() {}};class T3:public T2,public T1,public T0{public: virtual ~T3(){};};int main(){ T3 t; void *void_bse=&t; T0 *pt0=&t; T1 *pt1=&t; T2 *pt2=&t; T3 *pt3=&t; cout<<"the address of void_bse:"<<int(void_bse)<<endl; cout<<"the address of pt0:"<<int(pt0)<<endl; cout<<"the address of pt1:"<<int(pt1)<<endl; cout<<"the address of pt2:"<<int(pt2)<<endl; cout<<"the address of pt3:"<<int(pt3)<<endl; cout<<"the address of t:"<<int(&t)<<endl;}输出如下
the address of void_bse:2293536
the address of pt0:2293544
the address of pt1:2293540
the address of pt2:2293536
the address of pt3:2293536
the address of t:2293536
为什么同一个对象,因为指针的类型不一样,他们的地址值就不一样?
[解决办法]
这个是很正常的,对于多继承这个情况来说,不同的基类指针导致编译器需要调整该指针指向主要是为了保证所指的部分与指针类型保持一致从而保持类型的完整性
[解决办法]
父类的指针指向的是父级子对象在子类对象空间中的地址
你可以看看C++对象模型这本书
[解决办法]
[解决办法]
参考#1楼
另建议参阅深度探索C++对象模型,data layout章节
