[关闭]
@ltlovezh 2020-11-04T07:08:36.000000Z 字数 2098 阅读 1505

C++结构体初始化

C++


当使用结构体时,一定要在定义结构体变量时,对所有成员变量进行初始化,否则,成员变量是随机值,导致出现各种奇葩Bug。

  1. typedef struct Outer {
  2. int width;
  3. int height;
  4. int coordX;
  5. int coordY;
  6. } Outer;

如果只是定义Outer结构体变量,而未初始化,则其成员变量是随机值,如下所示:

  1. Outer outer; // 定义outer时,未初始化
  2. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);
  3. // 输出值,可见coordX和coordY是一些随机值
  4. width: 0, height: 0, coordX: -297638480, coordY: 32766

结构体的初始化整体分为:直接初始化和构造函数初始化。

直接初始化

在定义结构体变量时,给定初始值。

  1. // 默认初始化
  2. Outer outer{};
  3. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);
  4. // 输出值
  5. width: 0, height: 0, coordX: 0, coordY: 0
  6. // 顺序初始化,根据实参个数依次初始化结构体的成员变量,这里就是用0和1初始化width和height,剩余的成员变量使用默认值
  7. Outer outer1{0, 1};
  8. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer1.width, outer1.height, outer1.coordX, outer1.coordY);
  9. // 输出值
  10. width: 0, height: 1, coordX: 0, coordY: 0
  11. // 指定变量初始化,对指定成员变量初始化,其他成员变量使用默认值
  12. Outer outer2{.coordX = 0, .coordY =1};
  13. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer2.width, outer2.height,outer2.coordX, outer2.coordY);
  14. // 输出值
  15. width: 0, height: 0, coordX: 0, coordY: 1

构造函数初始化

在C++中,结构体与类在使用上已没有本质区别了,所以可以使用构造函数来初始化。

  1. typedef struct Outer {
  2. int width;
  3. int height;
  4. int coordX;
  5. int coordY;
  6. // 无参构造函数
  7. Outer() : width(1), height(2), coordX(3), coordY(4) {
  8. }
  9. // 两参构造函数
  10. Outer(int w, int h) : width(w), height(h), coordX(33), coordY(44) {
  11. }
  12. // 四参构造函数
  13. Outer(int w, int h, int x, int y) :
  14. width(w), height(h), coordX(x), coordY(y) {
  15. }
  16. } Outer;

可以通过以下方式初始化Outer结构体:

  1. // 下面两种方式都是调用无参构造函数
  2. Outer outer;
  3. Outer outer{};
  4. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);
  5. // 输出值
  6. width: 1, height: 2, coordX: 3, coordY: 4
  7. // 调用两参构造函数
  8. Outer outer1{0, 1};
  9. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer1.width, outer1.height, outer1.coordX, outer1.coordY);
  10. // 输出值
  11. width: 0, height: 1, coordX: 33, coordY: 44
  12. // 下面两种方式都是调用四参数构造函数
  13. Outer outer2{10,20,30,40};
  14. Outer outer2(10,20,30,40);
  15. printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer2.width, outer2.height,outer2.coordX, outer2.coordY);
  16. // 输出值
  17. width: 10, height: 20, coordX: 30, coordY: 40
  18. // 在包含构造函数的情况下,这种指定成员变量的初始化方式将不再支持,编译报错
  19. Outer outer3{.coordX = 0, .coordY =1};

总结

不管哪种初始化方式,一定要保证在定义结构体变量时就完成初始化,而不是定义之后再对每个成员变量赋值(这种情况下,如果有新增的成员变量,非常容易忘记对新增成员变量赋值默认值,从而导致新增成员变量是随机值)。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注