Structure [구조체]

Tips/C++ Eng2015.10.21 00:46

Arrays can store multiple pieces of data in one compound data type but recall, the data types must all be of the same type. If that is the case, how might you store multiple pieces of data in one type, where the individual pieces are of different data types? For example, let's say that we want to store information about a coffee bean. We might want to store information about the bean type, its strength, and perhaps which country it originated from. In this case, we could use all strings to store that information but what if the strength was intended to be a number from 1 to 10. In this case, we would want to store two strings and one integer in our coffee bean data type.

We haven't covered classes yet, which is another data type we could use, but instead, we will use a structure (struct) to store this information. Structures are known as user-defined types. You define the struct by giving it a name and then adding the member data types as in the following example:

struct coffeeBean 

     string name; 
     string country; 
     int strength; 

Recall that in order to use the string data type in our struct, the C++ file that contains the struct must include the string header file. This code snippet also assumes that using namespace std; has also been included.

Once we have defined the structure, we can then use it in our code the same as any other data type. To use the coffeeBean struct in your code, you simply declare a new variable of that type as shown in this example.

struct coffeeBean 

     string name; 
     string country; 
     int strength; 

coffeeBean myBean = { "Strata", "Columbia", 10 }; 
coffeeBean newBean; = "Flora"; = "Mexico"; 
newBean.strength = 9; 
cout << "Coffee bean " + + " is from " + << endl;

You can assign values to a struct using one of the methods seen here. For myBean, we assign values in the curly braces while for newBean, we use the dot notation. You can also access the values of the the struct members using the dot notation as well, shown in the cout statement at the end.

This contents come from edx : Introduction to C++

'Tips > C++ Eng' 카테고리의 다른 글

Enumerations  (0) 2015.10.27
Unions  (0) 2015.10.27
Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14


Posted by 비타오백

관련 글

댓글 영역

티스토리 툴바