Initialization C ++ structure

Speaking structure initialization, the natural structure can define a variable, then the assignment of the elements thereof individually, to achieve the purpose of the initialization; or assignment for read.

stu.id = 1;
stu.gender = 'M';

scanf("%d %c", &stu.id, &stu.gender);

However, if this is done, then when the body structure is not convenient when many variables, this time can be initialized using the constructor

The so-called constructor is used to initialize a functional structural body, it is defined directly in the structure. One feature is that it does not require a constructor returns a write type, and function name and the name of the same structure.

In general, the structure of a general definition, which is generated inside a default constructor (but not visible). It is because of the existence of this constructor can be defined directly StudentInfo types of variables not initialized (because it does not allow users to provide any initialization parameters).

struct StudentInfo {
    int id;
    char gender;
    StudentInfo() {}    // 默认生成的构造函数
}

Obviously, we only need to provide a variable initialization parameters to assign structures in the body, and can not conflict with existing variables.

Note: If you own redefined constructor, the initialization can not by definition structure variables , that is, the default constructor is generated at this time is covered. In order to define not only does not initialize structure variables, but also enjoy the convenience brought by the initialization, you can manually add the default constructor. This means that, as long as the number and type of parameters are not identical, can define as many constructors, to adapt to different situations initialization.

struct StudentInfo {
    int id;
    char gender;
    // 用以不初始化就定义结构体变量
    StudentInfo() {}            
    // 只初始化gender
    StudentInfo(char _gender) {
        gender = _gender;
    }
    // 同时初始化id和gender
    StudentInfo(int _id, char _gender) : id(_id), gender(_gender) {}
};

A common example, the definition of an array of structures :

struct Point {
    int x, y;
    Point() {}                  // 用以不经初始化地定义pt[10]
    Point(int _x, int _y) : x(_x), y(_y) {}     // 用以初始化x和y
}pt[10];
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105063349