50-C++对象模型分析(上)

回归本质

class是一种特殊的struct:

•  在内存中class依旧可以看作变量的集合

•  class与struct遵循相同的内存对其规则

•  class中的成员函数与成员变量是分开存放的:(1)每个对象有独立的成员变量(2)所有对象共享类中的成员函数

值得思考的问题?

 

【范例代码】对象内存布局初探

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class A {
 7     int i;
 8     int j;
 9     char c;
10     double d;
11 public:
12     void print() {
13         cout << "i = " << i << ", "
14              << "j = " << j << ", "
15              << "c = " << c << ", "
16              << "d = " << d << endl;
17     }
18 };
19 
20 struct B {
21     int i;
22     int j;
23     char c;
24     double d;
25 };
26 
27 int main(int argc, const char* argv[]) {
28     A a;
29 
30     cout << "sizeof(A) = " << sizeof(A) << endl;    // 20 bytes
31     cout << "sizeof(a) = " << sizeof(a) << endl;
32     cout << "sizeof(B) = " << sizeof(B) << endl;    // 20 bytes
33 
34     a.print();
35 
36     B* p = reinterpret_cast<B*>(&a);
37 
38     p->i = 1;
39     p->j = 2;
40     p->c = 'c';
41     p->d = 3;
42 
43     a.print();
44 
45     p->i = 100;
46     p->j = 200;
47     p->c = 'C';
48     p->d = 3.14;
49 
50     a.print();
51 
52     return 0;
53 }

C++对象模型分析

运行时的对象退化为结构体的形式:

•  所有成员变量在内存中依次排布

•  成员变量间可能存在内存间隙

•  可以通过内存地址直接访问成员变量

•  访问权限关键字在运行时失效

 

♦  类中的成员函数位于代码段中

♦  调用成员函数时对象地址作为参数隐式传递

♦  成员函数通过对象地址访问成员变量

♦  C++语法规则隐藏了对象地址的传递过程

【范例代码】对象本质分析

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class Demo {
 7     int mi;
 8     int mj;
 9 public:
10     Demo(int i, int j) {
11         mi = i;
12         mj = j;
13     }
14 
15     int getI() {
16         return mi;
17     }
18 
19     int getJ() {
20         return mj;
21     }
22 
23     int add(int value) {
24         return mi + mj + value;
25     }
26 };
27 
28 int main(int argc, const char* argv[]) {
29     Demo d(1, 2);
30 
31     cout << "sizeof(d) = " << sizeof(d) << endl;
32     cout << "d.getI() = " << d.getI() << endl;
33     cout << "d.getJ() = " << d.getJ() << endl;
34     cout << "d.add(3) = " << d.add(3) << endl;
35 
36     return 0;
37 } 
posted @ 2018-06-13 11:12  老姚大大  阅读(205)  评论(0编辑  收藏  举报