typedef struct point3d{ //数据 float x; float y; float z; }Point3d; void Point3d_print(const Point3d *pd{ printf("%g,%g,%g",pd->x,pd->y,pd->z); }
class Point3d{ float _x; float _y; float _z; public: void point3d_print(){ printf("%g,%g,%g",_x,_y,_z); } };
class A{}; // sizeof(A) = 1 有木有很奇怪?稍后说明 class B{int x;}; // sizeof(B) = 4 class C{ int x; public: int get(){return x;} }; // sizeof(C) = 4; 是不是验证了我们上述的论述?
A a,b; if(&a == &b)cout<<"error"<<endl;
class A{ char x; int y; char z; }; // sizeof(A) == 12; class B{ char x; char y; int z; }; // sizeof(B) = 8; class C{ int x; char y; char z; }; // sizeof(C) = 8; class D{ long long x; char y; char z; }; //sizeof(D) = 16; 由于longlong为8字节大小,此处以8字节对齐
class A{ static int x; }; //sizeof(A) = 1; class B{ int x; public: int get(){ return x; } }; //sizeof(B) = 4 class C{ int x; public: virtual int get(){ return x; } }; //sizeof(C) = 8;
class A{ void (*pf)(); //函数指针 }; //sizeof(A) = 4; class B{ int *p; // 指针 }; //sizeof(B) = 4;
class X{ int a; int b; public: virtual void foo1(){cout<<"X::foo1"<<endl;} virtual void foo2(){cout<<"X::foo2"<<endl;} };
#include<iostream> using namespace std; class X{ int _a; int _b; public: virtual void foo1(){cout<<"X::foo1"<<endl;} virtual void foo2(){cout<<"X::foo2"<<endl;} }; typedef void (*pf)(); int main(){ X a; int **tmp = (int **)&a; pf ptf; for(int i=0;i<2;i++){ ptf = (pf)tmp[0][i]; ptf(); } }
class A{ int x; }; class B:public A{ int y; }; //sizeof(B) = 8;我们来看看涉及到继承的时候内存的布局情况。
class C{ public: virtual void fooC(){ cout<<"C::fooC()"<<endl; } }; //sizeof(C) = 4; class D:public C{ int a; public: virtual void fooD(){ cout<<"D::fooD()"<<endl; } }; //sizeof(D) = 8;内存布局应该是这个样子:
typedef void (*pf)(); int main(){ C a; D b; int **tmpc = (int **)&a; int **tmpb = (int **)&b; pf ptf; ptf = (pf)tmpc[0][0]; ptf(); ptf = (pf)tmpb[0][0]; ptf(); ptf = (pf)tmpb[0][1]; ptf(); }运行结果:
class A{ int _a; public: virtual void fooA(){ cout<<"C::fooA()"<<endl; } virtual void poo(){ cout<<"A::poo()"<<endl; } }; //sizeof(A) = 8; class B{ int _b; public: virtual void fooB(){ cout<<"C::fooB()"<<endl; } virtual void poo(){ cout<<"B::poo()"<<endl; } }; ////sizeof(B) = 8; class C:public A,public B{ int _c; public: void poo(){ cout<<"C::poo()"<<endl; } virtual void hoo(){ cout<<"C::hoo()"<<endl; } }; //sizeof(C) = 20;
typedef void (*pf)(); int main(){ C a; int **tmp = (int **)&a; pf ptf; for(int i=0;i<3;++i){ ptf = (pf)tmp[0][i]; ptf(); } cout<<"-----------"<<endl; int s = sizeof(A)/4; //指针与int都占用4字节大小 for(int i=0;i<2;i++){ ptf = (pf)tmp[2][i]; ptf(); } }
class A{ int _a1; int _a2; }; //sizeof(A) = 8; class B:virtual public A{ int b; }; //sizeof(B) = 16; class C:virtual public A{ int c; }; //sizeof(C) = 16; class D:public B,public C{ int d; }; //sizeof(D) = 28;
int main(){ D d; A *pta = &d; B *ptb = &d; C *ptc = &d; cout<<"D: "<<&d<<endl; cout<<"B: "<<ptb<<" C: "<<ptc<<endl; cout<<"A: "<<pta<<endl; }
C++对象模型那点事儿(布局篇),布布扣,bubuko.com
原文地址:http://blog.csdn.net/blood_flowing/article/details/25654697