官术网_书友最值得收藏!

Structs

Structures or structs are used to group data together. A struct can have different data elements in it, called members, integers, floats, chars, and so on. You can create many objects of a similar struct and store values in the struct for data management.

The syntax of a struct is shown as follows:

struct name{ 
 
type1 name1; 
type2 name2; 
. 
. 
} ; 
 

An object of a struct can be created as follows:

struct_name     object_name; 

An object is an instance of a struct to which we can assign properties to the data types we created when creating the struct. An example of this is as follows.

In a situation in which you want to maintain a database of students' ages and the height of a section, your struct definition will look like this:

struct student { 
 
   int age; 
   float height; 
 
}; 

Now you can create an array of objects and store the values for each student:

int main() 
{ 
 
   student section[3]; 
 
   section[0].age = 17; 
   section[0].height = 39.45f; 
 
   section[1].age = 12; 
   section[1].height = 29.45f; 
 
   section[2].age = 8; 
   section[2].height = 13.45f; 
 
 
   for (int i = 0; i < 3; i++) { 
    
         std::cout << "student " << i << " age: " << section[i].age << " height: " << section[i].height << std::endl; 
   } 
 
 
   _getch(); 
   return 0; 
} 

Here is the output of this:

主站蜘蛛池模板: 东乌珠穆沁旗| 淳化县| 萝北县| 化德县| 布尔津县| 石屏县| 盐池县| 平舆县| 溆浦县| 平南县| 商南县| 兴城市| 三门县| 宁津县| 昭平县| 长岛县| 河南省| 金川县| 棋牌| 依安县| 青州市| 武胜县| 彩票| 华亭县| 黄骅市| 左权县| 曲周县| 台中县| 安康市| 衡山县| 肇州县| 紫云| 翁源县| 翼城县| 云阳县| 吉安市| 浦县| 香港 | 任丘市| 金华市| 临沭县|