Having studied the structure of C ++ in this lesson, in front of you of the slightly open space for creativity in programming. Prior to this lesson,, we could use standard (integrated) data types for the variables in their programs (int, float, char, bool). Now we learn how to create something like its own data type. This is done with the help of structures.
As always, at the beginning of the article explain why you might want to do this. Let's, you need to save the girl model data. We need to store such data about it: name, age, growth, weight, volumes and knowledge / ignorance of the English language. As you can see, all data models are different types: the name must be stored in an array of type char, volumes – in variables of type int, to mark on knowledge of English will suit a variable of type bool…
It turns out, what to store that data, array We won't be able to use, as it keeps the same type of data. Using the structure it is possible to group all the data, conditionally combined logical link, into one. Look:
To use the keyword structure definition struct. After you specify a descriptor (the name of the new data type). Name gives the programmer. It follows the same rules, as the names of variables. We handle structure – this is WonderfulWoman.
The braces are placed elements (members) structure – named variables or arrays of any C ++ data types. The structure can store different types of elements. As you can see in our structure there are elements of type int, char and bool. Terminates the definition of the structure of a semicolon ;
After, as the structure is defined, we can create variables of type structure – objects structure. They are created the same way, as well as variables such as bool, int, char… Writing descriptor (“type”) and give the name of the structure of an object. For example, in main-functions create variable
WonderfulWoman firstWoman; Here WonderfulWoman will play a role type, and firstWoman – the role of the declared variable.
The element structure may also be other object, certain previously, structure. That is, one can put structure to another. Consider the example. In it also will understand, how to access the elements of the structure, to record data therein, for example, and then display on the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #include<iostream> using namespace std; struct Size // эту структуру мы вложим в структуру WonderfulWoman { int breast; // объем груди int waist; // талии int hips; // бёдер }; struct WonderfulWoman { char name[32]; int age; int height; int weight; Size volume; // вложенная структура bool engKnowledge; }; void showData(const WonderfulWoman &Obj); int main() { setlocale(LC_ALL, "rus"); WonderfulWoman firstWoman = {}; // установит значения всех элементов структуры в 0 // присвоение значений элементам структуры strcpy_s(firstWoman.name, "Оксана"); firstWoman.age = 23; firstWoman.height = 172; firstWoman.weight = 55; firstWoman.engKnowledge = 1; // присвоение значений элементам вложенной структуры firstWoman.volume.breast = 90; firstWoman.volume.waist = 60; firstWoman.volume.hips = 90; showData(firstWoman); return 0; } void showData(const WonderfulWoman &Obj) { cout << "Модель: " << Obj.name << endl; cout << "Возраст: " << Obj.age << endl; cout << "Рост: " << Obj.height << endl; cout << "Вес: " << Obj.weight << endl; cout << "Объемы: " << Obj.volume.breast << '/' << Obj.volume.waist << '/' << Obj.volume.hips << endl; cout << "Английский (1 - да, 0 - нет): " << Obj.engKnowledge << endl; cout << endl; } |
Let's go in order. Strings 4 – 9: structure determinationSize. It contains three types of element int, which will be stored measurements model – the volume of the breast, waist, hips. This structure we put in underneath it with a structure – WonderfulWoman. It contains elements of different types – character array, type variables int, bool.
In string 17 declared object volume typeSize. This is the attachment structure. In 21-th string is the function prototype, which will display the structure of the dataWonderfulWoman the screen. About this function discussed below, when we come to its definition.
Line 27 – classified structure object: WonderfulWoman firstWoman = {}; Here it is clear: WonderfulWoman – descriptor (type), firstWoman – the structure of the object. This record = {}; install all the values of the structure elements WonderfulWoman to zero. Including, all the elements of a character array will be set to \0 . Since the objectvolumeIt is an element of structureWonderfulWoman, its elements will also be assigned zeros. That is such a record will clean all the elements of the structure from the debris (residual data from other programs).
Accessing the elements of structure. To record or retrieve the data we need to refer to a specific element of the structure of an object. To do this, use accessory operation . (point): firstWoman.age = 23; It is necessary for us to make the age data – write the name of the structure of an object, behind him . (point) and next the name of the element structure, which must be stored model number of years. To save the name – We use the library functionstrcpy_s() orstrcpy() (depending on your development environment).
Take a good look at the strings 36 – 38. There we assign values to elements of a nested structure. For example: firstWoman.volume.breast = 90; As before, we write the name of the structure of an object, behind him . (point). Then the name of the object nested structure, again . (point). Only now choose an element nested structure breast, which should address.
Last thing – structure can be transferred freely to the function, and return from the function, as ordinary variables. Defining a function for outputting the data structure on the screen – in strings 45 – 54. Since we need only show data and very desirable not to spoil them in the function, transmission structure using operator const. Calling a function is in string 40. Then just pass the object in the function structure, specifying its name. Result:
Homework for you: write another function for our program, in which the user is prompted to enter the model on data from the keyboard. Write data will have on the three models and display them on the screen.
In this video, we talked about the structures with the 4th minute:
In this article (the first part of the) we very superficially examined the structure of C ++. In morearticle (second part) about structures we will talk about the features of structure determination, about initializing objects structure, assignment of structures using transaction = and that how much memory is allocated for the object structure.
I was always afraid of new topics in C ++. So with structures ))) It was terrible and risen. I read there, there. Then he went to your website – as always, all short and clear. I look forward to the second part of the lesson on structures. And an array of structures are very interested :)
Hello! Prompt, and where did &Obj in 45 row? I thought it was a reference to the variable Obj, but she was nowhere to be announced. Generally, I'm confused with this. explain please.
Sorry, zatupil! Already I understood!
“Then just pass the object structure in the function, specifying its name”. But we have the name of the object structure – it firstWoman, and we pass Obj. And if there will be several objects, how to pass a specific one?
excuse me, reached
Hello! I am newbie, question, Is this code correctly adds feet and inches?
#include “stdafx.h”
#include
using namespace std;
struct Distance
{
int feet;
float inches;
};
Distance addengls(Distance, Distance);
void engldisp(Distance);
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(0, “”);
Distance d1, d2, d3;
cout <> d1.feet;
cout <> d1.inches;
cout <> d2.feet;
cout <> d2.inches;
d3 = addengls(d1, d2);
cout <<endl;
engldisp(d1); cout << " + ";
engldisp(d2); cout << " = ";
engldisp(d3); cout <= 12.0)
{
dd3.inches -= 12.0;
dd3.feet++;
}
dd3.feet += dd1.feet + dd2.feet;
return dd3;
}
void engldisp(Distance dd)
{
cout << dd.feet << "\'-" << dd.inches << "\"";
}
Um, but it didn't reach me.
Design &Obj has not been met anywhere before and here, without any explanation – nate, hawai.