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;
}
有两种数据成员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;
}
相关文章推荐
- c++对象模型(关于STRUCT和CLASS)
- C++对象模型——关于对象(第一章)
- C++对象模型——关于对象(第一章)
- 关于c++对象模型中指出的c++新手容易出现的误解之编译器不同处理
- C++对象模型之一 关于对象笔记
- C++对象模型——关于对象(第一章)
- 关于C++对象模型(中)
- 深入探索C++对象模型 第一章 关于对象
- 关于模板编程的一个例子 来自深度探索c++对象模型
- C++对象模型 -- 关于对象的概述
- 关于C++对象模型的思考
- 《深入探索C++对象模型》第一章:关于对象
- 深度搜索C++对象模型 - 关于对象
- C++ — 关于菱形虚拟继承对象模型的探究
- C++对象模型(1)——关于对象
- learning C++ 对象模型 of 关于对象
- 关于C++对象模型的一点理解(2)
- 深入探索C++对象模型笔记之二 —— 关于对象(下)
- 【深度探索C++对象模型】第一章 关于对象
- 深度搜索C++对象模型1-关于对象