chapter 11.pdf

结构体

声明:结构体名字,名称,

不完全类型:无法实例化,可以定义指针

定义:结构体内存结构,申请内存

翻译单元级别:在编译的时候只有一处定义,不同的cpp可以有各自的一种定义

image.png

结构体初始化:

类内初始化/聚合初始化/指派初始化

  1. struct Str; //结构体声明
  2. //结构体定义,包含结构体的内存结构
  3. struct Str
  4. {
  5. int x = 3;//类内初始化
  6. int y;
  7. };
  8. int main()
  9. {
  10. Str m_str{3,4};//聚合初始化,按顺序赋值,未赋值的缺省为0
  11. Str m_str{.x=3,.y=4}; //c++20,指派初始化,避免聚合初始化由于类结构调整导致赋值错误
  12. }

mutable限定符

可以改变常量结构体内成员的值

  1. struct Str
  2. {
  3. mutable int x=0;
  4. int y = 1;
  5. }
  6. int main()
  7. {
  8. const Str m_str;
  9. m_str.x = 3;
  10. }

静态数据成员

image.png
多个对象共享的数据成员

  1. struct Str
  2. {
  3. static int x;
  4. static const int array_size = 0;//const对象类内初始化,在数组声明时,需要确定array_size的值
  5. int buffer[array_size];
  6. int y = 1;
  7. };
  8. int Str::x; //类外定义
  9. int main()
  10. {
  11. Str m_str1;
  12. Str m_str2;
  13. m_str1.x = 100; //x是静态数据成员,所以m_str1与m_str2的值相同
  14. }

image.png
heap:动态申请的内存
stack:临时变量存储区域,virtual pointer