关于对象
有两种数据成员static和nonstatic,以及三种成员函数static、nonstatic和virtual。C++对象模型对内存空间和存取时间做了优化,nonstatic的数据成员被置于类对象之内,而static数据成员被置于类对象之外。函数则全部放在对象之外。下面的程序对此对了验证。
- #include <iostream>
- using namespace std;
- class test
- {
- public:
- static void f(){cout << "f() called" << endl;}
- void g(){cout << "g() called" << endl;}
- virtual void h(){cout << "g() called" << endl;}
- static int a;
- int b;
- int c;
- };
- int test::a = 1;
- int main()
- {
- test t;
- typedef void (*PFUN)();
- PFUN pfun = test::f;
- cout << "the address of staic void f(): " << pfun << endl;
- typedef void (test::*PFU)();
- PFU pfu = test::g;
- cout << "the address of void f(): " << pfu << endl;
- cout << "the address of virtual void h(): " << *(int*)(*(int*)(&t)) << endl;
- cout << "the address of static int a: " << (int*)(&test::a) << endl;
- cout << "the address of t: " << (int*)(&t) << endl;
- cout << "the address of int b: " << (int*)(&t.b) << endl;
- cout << "the address of int c: " << (int*)(&t.c) << endl;
- cout << "the offset of b: " << (char*)(&t.b)-(char*)(&t) << endl;
- cout << "the offset of c: " << (char*)(&t.c)-(char*)(&t) << endl;
- return 0;
- }