简体   繁体   中英

Understanding structures in CPP(c++)

i am leaning CPP(c++) programming language, now i am learning structures in CPP. I found one complex(for me) structure, can anyone explains this structure.

struct person {
           string name;
           int salary;
           int empid;
} employee[] = { { "abc", 1, 2 }, { "klm", 3, 4 } }
  1. What is this structure called (if there is any specific name. like array of structures)?
  2. How can i access data members inside it?
  3. How can i print the values(abc,klm......) directly(with "employee" if possible) and using struct variable?

In the example, the name of the structure type is person . The structure has 3 member variables, name , salary and empid of type string , int and int respectively.

Along with this type definition, a variable named employee is defined which is an array of type person . The size of the array is given by the size of initializer list (2 instances of person ) provided after the = .

However, the initialization is not valid because it attempts to assign values of type string to all members for both instances of the structure. It would instead have to be in the form of example { {"abc", 1, 2}, {"def", 3, 4} } .

The array will now hold 2 persons, employee[0] and employee[1] . Their member variables can be accessed/printed as follows:

  printf("Employee 0: name=%s, salary=%d, empid=%d\n", employee[0].name, employee[0].salary, employee[0].empid);

Modifying the initialization to something that actually builds, the code

struct person {
    string name;
    int salary;
    int empid;
} employee[] = { { "John Foo", 40000, 1 }, { "Claus Bar", 30000, 2 } };

Is equivalent to:

struct person {
    string name;
    int salary;
    int empid;
};

person employee[2] = { { "John Foo", 40000, 1 }, { "Claus Bar", 30000, 2 } };

That is, you define the structure person . Then you define and initialize the variable employee as an array of two person objects, each object initialized to certain values ( employee[0] will be John Foo, and employee[1] will be Claus Bar).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM