Lesson # 8. Structures

Дата изменения: 5 декабря 2020

Theory

Structures in C++

    Example:

    1
    2
    3
    4
    5
    6
    7
    
    struct product {
      int weight;
      double price;
    } ;
     
    product apple;
    product banana, melon;
    This declares a structure type, called product, and defines it having two members: weight and price, each of a different fundamental type. This declaration creates a new type (product), which is then used to declare three objects (variables) of this type: apple, banana, and melon. Note how once product is declared, it is used just like any other type.
  • Right at the end of the struct definition, and before the ending semicolon (;), the optional field object_names can be used to directly declare objects of the structure type. For example, the structure objects apple, banana, and melon can be declared at the moment the data structure type is defined:
  • 1
    2
    3
    4
    
    struct product {
      int weight;
      double price;
    } apple, banana, melon;
    In this case, where object_names are specified, the type name (product) becomes optional: struct requires either a type_name or at least one name in object_names, but not necessarily both.

Access to the objects’ members

  • Once the three objects of a determined structure type are declared (apple, banana, and melon) its members can be accessed directly. The dot notation is used. Dot (.) must be inserted between the object name and the member name. For example, we could operate with any of these elements as if they were standard variables of their respective types:
  • 1
    2
    3
    4
    5
    6
    
    apple.weight
    apple.price
    banana.weight
    banana.price
    melon.weight
    melon.price
    Each one of these has the data type corresponding to the member they refer to: apple.weight, banana.weight, and melon.weight are of type int, while apple.price, banana.price, and melon.price are of type double.

    Pointers to structures

  • Structures can be pointed to by its own type of pointers:
  • 1
    2
    3
    4
    5
    6
    7
    
    struct Product_t {
      int weight;
      double price;
    } apple, banana, melon;
     
    Product_t aproduct;
    Product_t * pproduct;
    Here aproduct is an object of structure type Product_t, and pproduct is a pointer to point to objects of structure type Product_t.
  • Therefore, the following code would also be valid:
  •  
    pproduct = &aproduct;
    
    The value of the pointer pproduct would be assigned the address of object aproduct.
  • The following example serve to introduce a new operator: the arrow operator (->):
  • //...
    struct Product_t {
      int weight;
      double price;
    } ;
     
    int main ()
    {
      string mystr;
     
      Product_t aproduct;
      Product_t * pproduct;
      pproduct = &aproduct;
     
      cout << "Enter weight: ";
      cin >> pproduct ->weight;
      cout << "Enter price: ";
      cin >> pproduct ->price;
     
      cout << "\nYou have entered:\n";
      cout << pproduct ->weight << " ";
      cout << pproduct ->price;
     
      return 0;
    }

    Labs and tasks

    Lab 1:
    To do: Create a Books_t structure for storing data about the books. Add the following properties (members) of an object:

    • book’s title
    • year of work

    Tasks:

    1. Create a Books_t structure
    2. Implement a method for printing out the information about the objects:
    3. void printBook(Books_t book);
    4. Specify two object names (e.g. Pushkin, Chekhov).
    5. In the main program, create at least 2 objects, display summaries on those books.

    Expected output:

    Lab 1:
    Enter year of Chekhov work Three Sisters:
    1897
    Pushkin's work is:
     Eugene Onegin 1823
    And Chekhov's:
     Three Sisters 1897
    

    ✍ How to do:

    • To do the lab create empty console application with a name Lesson8. Add files: main8.cpp, structBooks8.cpp, structBooks8.h.
    • Include all the needed libraries and files.
    • 1. Create a structure Books_t for storing data about the books. Add the following properties (members) of an object: book’s title, year of work.

    • The structure must be defined inside a header file. So, open the structBooks8.h and add the code to define the structure with two members, they are title and year:
    • struct Books_t
      {
      	string title;
      	int year;
      };
      

      2. Implement a method for printing out the information about the objects.

    • Also inside the header file you should define the method with a parameter of Books_t type, to accept a particular book from the main program. Add the code after the structure:
    • //method for printing out the information about the objects
      void printBook(Books_t book);
      
    • The implementation of the function should be placed into the structBooks8.cpp file:
    • void printBook(Books_t book)
      {
      	cout << book.title;
      	cout << " " << book.year << endl;
      }
      

      3. Specify two object names (e.g. Pushkin, Chekhov).

    • Open the main.cpp file and inside the main function add the code to create two objects of the structure type:
    • Books_t Pushkin;
      Books_t Chekhov;
      

      4. In the main program, create at least 2 books, display summaries on these books.

    • After the objects' definitions add the code to initialise the members (fields) with the particular values. Ask user to enter one of the fields value, e.g. the year of the book:
    • Pushkin.title = "Eugene Onegin";
      Pushkin.year = 1823;
      
      Chekhov.title = "Three Sisters";
      cout << "Enter year of Chekhov work Three Sisters: "<cin >> Chekhov.year;
      
    • Print out the information about the books using the printBook method:
    • cout << "Pushkin's work is:\n ";
      printBook(Pushkin);
      cout << "And Chekhov's:\n ";
      printBook(Chekhov);
      
      system("pause");
      
    • Add the code to return a value 0 inside the main function. Run the program and check the output.
    Task 1:

    To do: Create a Cars_t structure to store an information about the cars. Add the members (fields) about the car's color, car's brand and year of issue. Create at least 4 objects and output information about those objects, using a printCars method.

    Note: The signature of the printCars method should be as follows:

    void printCars(Cars_t car);

    Expected output:

    Task 1:
    Enter car's brand:
    >>audi
    Enter car's color:
    >>grey
    Enter car's year of issue:
    >>1997
    Summary info:
    audi grey 1997
    bmw green 2009
    suzuki white 2015
    honda black 2019
    

    [Solution and Project name: Lesson_8task1, file name L8Task1main.cpp, L8Task1imp.cpp, L8Task1.h]

    Lab 2, arrays of structure type:

    To do: Create a Toys_t structure for storing data about the toys for sale. Add the following properties (members) of an object:

    • toy's title of string type
    • age of children to play with that toy (integer type)

    Tasks:

    1. Implement a method for printing out the information about the objects:
    2. void printBook(Toys_t toy);
    3. Implement a method for printing out the toys for small children (up to 4 years old):
    4. void printToy4(Toys_t toy);
    5. Specify an array of objects toys. Because structures are types, they can also be used as the type of arrays to construct tables or databases of them.
    6. In the main program, create at least 4 elements of the array, display summaries on those toys.

    Expected output:

    Enter toy's title:
    >>cat
    Enter child's age:
    >>2
    Summary info:
    car 3
    doll 4
    crocodile 6
    cat 2
    Summary info for small children:
    car 3
    doll 4
    cat 2
    

    ✍ How to do:

    • To do the lab create empty console application with a name Lesson8Toys. Add files: main8.cpp, structToys8.cpp, structToys8.h.
    • Include all the needed libraries into the code of those files.
    • 1. Create a Toys_t structure for storing data about the toys for sale

    • The structure must be defined inside a header file. So, open the structToys8.h and add the code to define the structure with two properties (members), they are title and age:
    • struct Toys_t
      {
      	string title;
      	int age;
      };
      

      2. Implement a method for printing out the information about the objects.

    • Also inside the header file you should define the method with a parameter of Toys_t type, to accept a particular toy from the main program. Add the code after the structure:
    • //method for printing out the information about the objects
      void printToys(Toys_t toy);
      
    • The implementation of the function should be placed into the structToys8.cpp file:
    • void printToys(Toys_t toy)
      {
      	cout << toy.title;
      	cout << " " << toy.age << endl;
      }
      

      3. Implement a method for printing out the toys for small children (up to 4 years old)

    • Inside the header file define the method with a parameter of Toys_t type:
    • //method for printing out the toys for small children
      void printToy4(Toys_t toy);
      
    • The implementation of the function should be placed into the structToys8.cpp file:
    • void printToy4(Toys_t toy)
      {
      	if (toy.age <= 4) {
      		printToys(toy);
      	}
      }
      

      4. Specify an array of objects toys.

    • Open the main.cpp file and inside the main function add the code to create an array of objects of the structure type:
    • Toys_t toys[4];
      

      5. In the main program, create at least 4 elements of the array, display summaries on those toys.

    • After the objects' definitions add the code to initialise the members (fields) with the particular values. Ask user to enter the values of one array element:
    • toys[0].title = "car";
      toys[0].age = 3;
      toys[1].title = "doll";
      toys[1].age = 4;
      toys[2].title = "crocodile";
      toys[2].age = 6;
      cout << "Enter toy's title: " << endl;
      cin >> toys[3].title;
      cout << "Enter child's age: " << endl;
      cin >> toys[3].age;
      
    • Print out the information about the toys using the printToys method, and information about the toys for small children:
    • cout << "Summary info:\n ";
      for (auto x: toys)
      	printToys(x);
      cout << "Summary info for small children:\n ";
      for (auto x : toys)
      	printToy4(x);
      
      system("pause");
      
    • Add the code to return a value 0 inside the main function. Run the program and check the output.
    Task 2:

    To do: Create a Tours_t structure to store an information about the tours for tourists. Add the members (fields) to implement the following info about the tour: country name, number of people, number of days, country rate (of double type). Create a method to print the data, and also method of the structure to calculate the cost of a trip based on: number of people * number of days * country rate. Inside the main function specify an array of objects tours. Both methods must be called for the array elements.

    Note: The signature of the printTourCost method should be as follows:

    // returnes the result of calculation, double type
    double printTourCost(Tours_t tour);

    Expected output:

    Task 2:
    Summary info:
     Sweden: people 2, days 3, rate 155.5
     the price is 933
    Norway: people 1, days 3, rate 265.5
     the price is 796.5
    UK: people 2, days 4, rate 455.5
     the price is 3644
    

    [Solution and Project name: Lesson_8task2, file names L8Task2main.cpp, L8Task2imp.cpp, L8Task2.h]

    Lab 3, Pointers to structures:

    To do: Create a Movies_t structure for storing data about the movies. Add the following properties (members) of an object:

    • movie's title of string type
    • the year of issue (integer type)

    Specify an array of movies (ask user to enter the info of one film). Implement a method for printing out the information about the objects, use the pointer to those objects and arrow operator.

    Expected output:

    Please, enter a title: 
    >>Matrix
    Please, enter year: 
    >>1999
    
    Summary information:
    Matrix 1999
    Titanic 1997
    

    ✍ How to do:

    • To do the lab create empty console application with a name Lesson8Movies. Add files: mainMovies8.cpp, structMovies8.cpp, structMovies8.h.
    • Include all the needed libraries into the code of those files.
    • The structure must be defined inside a header file. So, open the structMovies8.h and add the code to define the structure with two properties (members), they are title and year:
    • struct Movies_t {
      	string title;
      	int year;
      };
      
    • Also inside the header file, you should define the method with a parameter of Movies_t type, to accept an array of movies from the main program. Add the code after the structure:
    • //method for printing out the information about the movies array with n elements
      void printMovies(Movies_t* movie, int n);
      
    • The implementation of the function should be placed into the implementation - structMovies8.cpp file:
    • void printMovies(Movies_t* array, int n) {
      	Movies_t *ptr = array;
      	for (int i = 0; i < 2; i++) {
      		cout << ptr->title << " " << ptr->year << endl;
      		ptr++;
      	}
      }
      
      *ptr is a pointer to point at the location which *array pointer points at.
      The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members. This operator serves to access the member of an object directly from its address.
    • Open the mainMovies8.cpp file and inside the main function add the code to create an array of objects of the structure type and a pointer to point at that array:
    • Movies_t amovie[3];
      Movies_t * pmovie;
      
      pmovie = amovie;
      
    • After the objects' definitions add the code to initialise the properties (fields) with the particular values. Ask user to enter the values of one array element:
    • amovie[1].title = "Titanic";
      amovie[1].year = 1997;
      cout << "Enter title: ";
      cin >> pmovie->title;
      cout << "Enter year: ";
      cin >> pmovie->year;
      
    • Print out the information about the movies using the printMovies method:
    • cout << "\nThe summary:\n";
      printMovies(amovie, 2);
      
      system("pause");
      
    • Add the code to return a value 0 inside the main function. Run the program and check the output.
    Task 3:

    To do: Create an Employee_t structure to store an information about the employees of some company. Add the members (fields) to implement the following info about the employees: name, department, phone, salary. Specify an array of employees. Implement a method for printing out the information about the objects, use the pointer to those objects and arrow operator. Also, create a smallSalary method to print out information about the employees, whose salary is less than 30 000 roubles.

    Note: The signature of the smallSalary method should be as follows:

    void smallSalary(Employee_t* array, int n);

    Expected output:

    Task 3:
    Summary info:
    Ivanov: bookkeeping department, t. 233-33-33, 28000 roubles
    Petrov: IT department, t. 233-33-34, 45000 roubles
    Sidorov: client department, t. 233-33-35, 25000 roubles
    
    Salary is less than 30 000 roubles:
    Ivanov
    Sidorov
    

    [Solution and Project name: Lesson_8task3, file names L8Task3main.cpp, L8Task3imp.cpp, L8Task3.h]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить