C++----類的成員變數和成員函式在類的儲存方式
阿新 • • 發佈:2018-12-14
類的成員變數和成員函式在類的儲存方式為分開儲存。
即只有非靜態變數儲存在類中,其餘的所有成員均不在類中。
實驗如下:
exp1:
class Person1
{
};
void test01()
{
cout << "size of (空類Person)是:" << sizeof(Person1) << endl;
}
//空類的大小是1,每個例項的物件,都有獨一無二的地址。
//每個地址,都有第一無二的char 來維護這個地址。
//這就是空類的大小;
exp2:
class Person2 { public: int m_Age; }; void test02() { cout << "size of Person2 是:" << sizeof(Person2) << endl; }
//執行結果為 4 ;
//m_Age 屬於非靜態的成員變數,屬於物件身上;
exp3:
class Person3
{
public:
int m_Age;
void func(){}
};
void test03()
{
cout << "size of Person3 是:" << sizeof(Person3) << endl;
}
//結果還是4;
//成員屬性和成員函式是分開儲存的;
//非靜態的成員函式不屬於物件身上;
exp4:
class Person4 { public: int m_Age; void func() {}; static int m_B; }; void test04() { cout << "size of Person4 是:" << sizeof(Person4) << endl; }
//結果還是4;
//說明靜態的變數為共享資料,不是物件(類)身上的東西
exp5:
class Person5
{
public:
int m_Age;
void func() {};
static int m_B;
static void func2() {};
};
void test05()
{
cout << "size of Person5 是:" << sizeof(Person5) << endl;
}
//結果還是4;
//靜態成員函式也不屬於物件。
//結論:只有非靜態成員變數才屬於物件。
//其餘的都不歸屬於物件。
exp6:
class Person6
{
public:
int m_Age;
void func() {};
static int m_B;
static void func2() {};
double m_C;
};
void test06()
{
cout << "size of Person6 是:" << sizeof(Person6) << endl;
}
//答案是16,原因是位元組對齊。
//****kkkk(int)+********(double)
int main()
{
test01();
test02();
test03();
test04();
test05();
test06();
return 0;
}
//end