您的位置:首页 > 编程语言 > C语言/C++

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

2009-08-24 01:35 211 查看
关于对象

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

Code:

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: