How to initialize a C++ struct?
There are several ways to initialize a C++ struct:
- Using default member initialization: it is possible to assign initial values to member variables when defining a structure. For example:
struct MyStruct {
int value1 = 10;
float value2 = 3.14f;
};
MyStruct obj; // 成员变量value1的值为10,value2的值为3.14
- Using member initialization lists: you can assign values to the members of a structure when defining a structure object through a member initialization list. For example:
struct MyStruct {
int value1;
float value2;
MyStruct(int v1, float v2) : value1(v1), value2(v2) {}
};
MyStruct obj(10, 3.14f); // 成员变量value1的值为10,value2的值为3.14
- With the assignment operator, you can assign values to the members of a structure after defining the structure object. For example:
struct MyStruct {
int value1;
float value2;
};
MyStruct obj;
obj.value1 = 10;
obj.value2 = 3.14f; // 成员变量value1的值为10,value2的值为3.14
It should be noted that the default constructor of a struct (a constructor with no parameters) will only be automatically generated when no other constructors are defined. If a constructor with parameters is defined, then the default constructor needs to be implemented manually.