现在的位置: 首页 > 综合 > 正文

C++对象模型—-关于对象

2013年11月27日 ⁄ 综合 ⁄ 共 1201字 ⁄ 字号 评论关闭

关于对象

 有两种数据成员staticnonstatic,以及三种成员函数staticnonstaticvirtualC++对象模型对内存空间和存取时间做了优化,nonstatic的数据成员被置于类对象之内,而static数据成员被置于类对象之外。函数则全部放在对象之外。下面的程序对此对了验证。

Code:
  1. #include <iostream>   
  2. using namespace std;   
  3. class test   
  4. {   
  5. public:   
  6.     static void f(){cout << "f() called" << endl;}   
  7.     void g(){cout << "g() called" << endl;}   
  8.     virtual void h(){cout << "g() called" << endl;}   
  9.     static int a;   
  10.     int b;   
  11.     int c;   
  12. };   
  13. int test::a = 1;   
  14. int main()   
  15. {   
  16.     test t;   
  17.     typedef void (*PFUN)();   
  18.     PFUN pfun = test::f;   
  19.     cout << "the address of staic void f(): " << pfun << endl;   
  20.     typedef void (test::*PFU)();   
  21.     PFU pfu = test::g;   
  22.     cout << "the address of void f(): " << pfu << endl;   
  23.     cout << "the address of virtual void h(): " << *(int*)(*(int*)(&t)) << endl;   
  24.     cout << "the address of static int a: " << (int*)(&test::a) << endl;   
  25.     cout << "the address of  t: " << (int*)(&t) << endl;   
  26.     cout << "the address of int b: " << (int*)(&t.b) << endl;   
  27.     cout << "the address of int c: " << (int*)(&t.c) << endl;   
  28.     cout << "the offset of b: " << (char*)(&t.b)-(char*)(&t) << endl;   
  29.     cout << "the offset of c: " << (char*)(&t.c)-(char*)(&t) << endl;   
  30.     return 0;   
  31. }  

 

抱歉!评论已关闭.