類(lèi)中成員變量和成員函數(shù)在內(nèi)存中的地址
#include <iostream>
using namespace std;
class Test
{
public:
int a;
int b;
void print();
void s();
void ss();
void fs();
};
void Test::print()
{
//cout << "hello" << endl;
}
void Test::s()
{
}
void Test::ss()
{
}
void Test::fs()
{
}
void f()
{
int s = 3;
cout << "&s" << &s << endl;
cout << "f" << endl;
}
class B:Test
{
};
int main()
{
Test t;
cout << sizeof(t) << endl;
cout << &t.a << endl;
cout << &t.b << endl;
Test tt;
cout << &tt.a << endl;
cout << &tt.b << endl;
typedef void (Test::*p)(void);
////Test t;
////t.print();
p fun = &Test::print;
printf("%p\n",fun);
fun = &Test::s;
printf("%p\n",fun);
fun = &Test::ss;
printf("%p\n",fun);
fun = &Test::fs;
printf("%p\n",fun);
f();
cout << "--------" << endl;
B b;
cout << sizeof(b) << endl;
////((Test::*print)fun)();
//Test *p4;
//fun(p4);
// Test t;
// (t.*fun)();
// Test d;
// (d.*fun)();
}
類(lèi)的成員函數(shù)不是在類(lèi)實(shí)例化的時(shí)候載入內(nèi)存的。應(yīng)該是編譯鏈接的時(shí)候就在程序文件中確定了相對(duì)地址。然后程序載入的時(shí)候,所有的函數(shù)都載入到內(nèi)存的代碼區(qū)。所以實(shí)例化對(duì)象的時(shí)候,只是申請(qǐng)了對(duì)象的成員變量的地址,成員函數(shù)對(duì)于所有的類(lèi)對(duì)象來(lái)說(shuō),應(yīng)該只有一份,在代碼區(qū)共用。而且類(lèi)的成員變量和成員函數(shù)不是存放在一起(地址不是連續(xù)的,是分開(kāi)存放的)
Test類(lèi)中的a,b變量地址是連續(xù)的,每個(gè)占4字節(jié)。但是s(),ss(),fs()不是和a,b連續(xù)的,而且,這些函數(shù)之間,好像也并不是嚴(yán)格連續(xù)的,改一下函數(shù)名,地址有可能會(huì)變化
posted on 2011-03-25 19:57 MrRightLeft 閱讀(1095) 評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi): C/C++

