@ltlovezh
        
        2020-11-04T07:08:36.000000Z
        字数 2098
        阅读 1808
    C++
当使用结构体时,一定要在定义结构体变量时,对所有成员变量进行初始化,否则,成员变量是随机值,导致出现各种奇葩Bug。
typedef struct Outer {int width;int height;int coordX;int coordY;} Outer;
如果只是定义Outer结构体变量,而未初始化,则其成员变量是随机值,如下所示:
Outer outer; // 定义outer时,未初始化printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);// 输出值,可见coordX和coordY是一些随机值width: 0, height: 0, coordX: -297638480, coordY: 32766
结构体的初始化整体分为:直接初始化和构造函数初始化。
在定义结构体变量时,给定初始值。
// 默认初始化Outer outer{};printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);// 输出值width: 0, height: 0, coordX: 0, coordY: 0// 顺序初始化,根据实参个数依次初始化结构体的成员变量,这里就是用0和1初始化width和height,剩余的成员变量使用默认值Outer outer1{0, 1};printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer1.width, outer1.height, outer1.coordX, outer1.coordY);// 输出值width: 0, height: 1, coordX: 0, coordY: 0// 指定变量初始化,对指定成员变量初始化,其他成员变量使用默认值Outer outer2{.coordX = 0, .coordY =1};printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer2.width, outer2.height,outer2.coordX, outer2.coordY);// 输出值width: 0, height: 0, coordX: 0, coordY: 1
在C++中,结构体与类在使用上已没有本质区别了,所以可以使用构造函数来初始化。
typedef struct Outer {int width;int height;int coordX;int coordY;// 无参构造函数Outer() : width(1), height(2), coordX(3), coordY(4) {}// 两参构造函数Outer(int w, int h) : width(w), height(h), coordX(33), coordY(44) {}// 四参构造函数Outer(int w, int h, int x, int y) :width(w), height(h), coordX(x), coordY(y) {}} Outer;
可以通过以下方式初始化Outer结构体:
// 下面两种方式都是调用无参构造函数Outer outer;Outer outer{};printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer.width, outer.height, outer.coordX, outer.coordY);// 输出值width: 1, height: 2, coordX: 3, coordY: 4// 调用两参构造函数Outer outer1{0, 1};printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer1.width, outer1.height, outer1.coordX, outer1.coordY);// 输出值width: 0, height: 1, coordX: 33, coordY: 44// 下面两种方式都是调用四参数构造函数Outer outer2{10,20,30,40};Outer outer2(10,20,30,40);printf("width: %d, height: %d, coordX: %d, coordY: %d\n", outer2.width, outer2.height,outer2.coordX, outer2.coordY);// 输出值width: 10, height: 20, coordX: 30, coordY: 40// 在包含构造函数的情况下,这种指定成员变量的初始化方式将不再支持,编译报错Outer outer3{.coordX = 0, .coordY =1};
不管哪种初始化方式,一定要保证在定义结构体变量时就完成初始化,而不是定义之后再对每个成员变量赋值(这种情况下,如果有新增的成员变量,非常容易忘记对新增成员变量赋值默认值,从而导致新增成员变量是随机值)。
