c++

c++内存布局

Posted by Roy Zhang on 2019-08-08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using namespace std;

class Point3d
{
public:
Point3d( float x=0.0, float y=0.0, float z=0.0)
: _x(x), _y(y), _z(z) { }

float *x_addr() { return &_x; }
float *y_addr() { return &_y; }
float *z_addr() { return &_z; }

float x() { return _x; }
float y() { return _y; }
float z() { return _z; }

void x( float xval ) { _x = xval; }
void y( float yval ) { _y = yval; }
void z( float zval ) { _z = zval; }

void Point3d_print() {
printf ("点坐标:(%g, %g, %g)\n", _x, _y, _z);
}

private:
float _x;
float _y;
float _z;
};

int main()
{
cout << "sizeof(Point3d) = " << sizeof(Point3d) << endl << endl;

//C++中可以直接声明一个类对象
Point3d pt(1, 2, 3);
pt.Point3d_print();
cout << "pt的内存大小:" << sizeof(pt) << endl;
cout << "pt._x成员的值" << pt.x() << ",地址:" << pt.x_addr() << endl;
cout << "pt._y成员的值" << pt.y() << ",地址:" << pt.y_addr() << endl;
cout << "pt._z成员的值" << pt.z() << ",地址:" << pt.z_addr() << endl << endl;

//也可以动态根据类指针在运行时申请内存创建一个对象
Point3d *_pt = new Point3d(4, 5, 6);
_pt->Point3d_print();
cout << "_pt指向的对象的内存大小:" << sizeof(*_pt) << endl;
cout << "_pt._x成员的值" << pt.x() << ",地址:" << pt.x_addr() << endl;
cout << "_pt._y成员的值" << pt.y() << ",地址:" << pt.y_addr() << endl;
cout << "_pt._z成员的值" << pt.z() << ",地址:" << pt.z_addr() << endl << endl;
delete _pt;

system("pause");
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
sizeof(Point3d) = 12

点坐标:(1, 2, 3)
pt的内存大小:12
pt._x成员的值1,地址:0x75292d1743b0
pt._y成员的值2,地址:0x75292d1743b4
pt._z成员的值3,地址:0x75292d1743b8

点坐标:(4, 5, 6)
_pt指向的对象的内存大小:12
_pt._x成员的值1,地址:0x75292d1743b0
_pt._y成员的值2,地址:0x75292d1743b4
_pt._z成员的值3,地址:0x75292d1743b8

一个总结https://blog.csdn.net/token2012/article/details/6124175