Теория
Лабораторные работы
Выполнить: Создайте класс
Rectangle
и объект (т.е. переменную) rect
этого класса.1) Класс должен содержать четыре поля:
— два поля данных типа
int
(поле width
и поле height
) с модификатором доступа private
,— и две функции-члена с модификатором доступа
public
: функции set_values
и area
.
2) Опишите определение двух функций: set_values
— функция должна устанавливать значения для полей width
и height
; area
— функция должна возвращать width * height
.
3) Создайте конструктор по умолчанию для класса, для инициализации полей width
и height
значениями (установите их равными 5).
4) Установите значения для свойств width
и height
объекта rect
и выведите информацию об этом объекте.
Пример вывода:
Лабораторная работа 1: ширина: >> 20 высота: >> 2 площадь rect: 40
✍ Алгоритм:
- To do the lab create empty console application with a name
Lesson9
. Add files:mainLab1.cpp
,ImpLab1.cpp
,HeaderLab1.h
. - Include all the needed libraries and files.
- The class must be defined inside a header file. So, open the header file and add the code to define the class with two private data members, they are
width
andheight
; and two member functions with public access, they areset_values
andarea
. - Here
Rectangle
is the class name (i.e., the type). - The functions
set_values
andarea
have a public access, it means that they can be accessed from inside the main function by simply inserting a dot (.
) between object name and member name (e.g.rect.set_values
…). width
andheight
members cannot be accessed from outside the class, since they have private access and they can only be referred to from within other members of that same class.- Since members
width
andheight
have private access, access to them from outside the class is not allowed. So, we should define a member function to set values for those members within the object: the member functionset_values
. - Let’s create the definition of
set_values
member function. We’re going to have a member of a class outside the class itself, so, we have to use scope operator (::
, two colons). You should create the definition of the function inside the implementation file: - The second member function, that is
area
function, we’re going to have inside the class itself, just to try different ways of definition. So, return to the header file and add the definition inside the class next toint area(void)
statement: - Add the declaration of a Custom default constructor inside the public access of the class (header file):
- Open your implementation file to add the definition of that constructor:
- Open a main file in the editor window. You should create an object (i.e., a variable) of the
Rectangle
class, calledrect
. And after this, ask user to input thewidth
andheight
values. Call theset_values
function and output the result: - Run the program and check the output.
1.Create a Rectangle
class:
class Rectangle { private: int width, height; public: void set_values(int, int); int area(void); } ;
2. Define two member functions:
void Rectangle::set_values(int x, int y) { width = x; height = y; }
::
) specifies the class to which the member being defined belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, the function set_values
has access to the variables width
and height
, which are private members of class Rectangle
, and thus only accessible from other members of the class, such as this.int area() {return width*height;}
3) Create a Custom default constructor to have the initial values for width
and height
(set them to 5
).
public: // you had this code Rectangle(); void set_values(int, int); // you had this code //...
Rectangle::
{
width = 5;
height = 5;
}
4) Set the width
and height
values for the rect
object and print out the information about this object:
int main() { Rectangle rect; int w, h; cout << "please, enter width:\n"; cin >> w; cout << "please, enter height:\n"; cin >> h; rect. (w, h); cout << "rect area: " << rect.area() << endl; system("pause"); return 0; }
Выполнить: Создайте класс LessonDate
для вывода даты урока.
1) Класс должен содержать следующие поля и функции:
— три поля типа int
с модификатором доступа private
:day
, month
и year
;
— и две функции-члена с модификатором доступа public:
void setDate(int, int, int);
чтобы назначить дату следующего урока и
void getDate();
чтобы вывести дату урока.
2) Создайте конструктор класса с тремя аргументами для задания начальных значений даты; в теле конструктора вызовите функцию setDate
для установки даты.
3) Внутри функции main
создайте объект (т.е. переменную) objLesson
этого класса. Задайте значения трех параметров — день, месяц и год. Выведите информацию об этом объекте.
Пример вывода:
Задание 1: Дата урока: 11.11.2021 Введите день, месяц и год следующего урока: 28 12 2020 Дата урока: 28.12.2020
[Solution and Project name: Lesson_10task1
, file name L10Task1main.cpp
, L10Task1imp.cpp
, L10Task1.h
]
Выполнить: Создать класс
Cube
.1) Класс должен содержать одно поле и три функции-члена класса
—
length_
— поле с типом double с модификатором доступа private,— три функции с модификатором доступа public: функция
double getVolume();
— для подсчета объема куба, функция double getSurfaceArea();
— для вычисления площади поверхности куба и void setLength(double length);
— для установления значения длины стороны куба.
2) Создайте определения (реализации) для функций:
getVolume()
: length_ * length_ * length_;
getSurfaceArea()
: 6 * length_ * length_;;
setLength(double length)
устанавливает значение длины стороны куба.
3) Создайте пользовательский конструктор по умолчанию, в котором поле length_
инициализируется значением (установите его равным 1).
4) В основном cpp-файле создайте функцию double cube_on_stack()
для создания объекта (т.е. переменной) этого класса и получения его объема. Этот объект будет находиться в памяти стека. Кроме того, в функции main
создайте новый куб длиной 10, который будет находиться в памяти кучи. Задайте значения. Выведите информацию об этих объектах.
5) Создайте пользовательский деструктор для удаления информации о кубе.
Пример вывода:
Лабораторная работа 2: Объем куба c: Деструктор, вызванный для куба длиной 2 Объем куба c в памяти кучи: 27 Деструктор, вызванный для куба длиной 3
✍Алгоритм:
- To do the lab create an empty console application with a name
Lesson9Lab2
. Create new files:mainLab2.cpp
,ImpLab2.cpp
,HeaderLab2.h
. - Include all the needed libraries and files.
- The interface of the class must be inside a header file. So, open the header file and add the code to define the class with one private data member, it is
length_
of a cube; and three member functions with public access, they aregetVolume()
,getSurfaceArea()
andsetLength(double length)
. - Here
Cube
is the class name (i.e., the type. - The functions
getVolume()
,getSurfaceArea()
andsetLength(double length)
have a public access, it means that they can be accessed from anywhere where the object is visible. length_
member cannot be accessed from outside the class, since it has a private access and it can only be accesses from within the class itself.- Let’s create the definition of
setLength
member function. We’re going to have a member of a class outside the class itself, so, we have to use scope operator (::
, two colons). You should create the definition of the function inside the implementation cpp file: - The second and th third member functions are
getVolume
andgetSurfaceArea
function, we’re going to have them inside the implementation file too: - Add the declaration of a custom default constructor inside the public access of the class (header file):
- Open your implementation file to add the definition of that constructor:
- Open a main file in the editor window. Before the main function add the code to create cube_on_stack() which will create the object of Cube class and return the volume of this object:
- Inside the main function ptint out the message and call that function:
- Then, inside the main function you should create a new cube of length 10 which is going to be in heap memory:
- Open header file to declare a class destructor, which will be called to clean up the instance of the class. Add it right after the class constructor to the public protection level:
- Add the implementation for that destructor inside implementation file:
- Return to the main file and add the
delete
keyword to clean up the memory of thepcube
object: - Run the program and check the output.
1.The class should contain four members:
class Cube { public: double getVolume(); double getSurfaceArea(); void setLength(double length); private: double length_; };
2. Give the definitions (implementations) of the functions:
void Cube:: (double length) { length_ = length; }
::
) specifies the class to which the member being defined belongs, granting exactly the same scope properties as if this function definition was directly included within the class definition. For example, the function setLength
has access to the variable length_
, which is a private member of the class Cube
, and thus only accessible from other members of the class, such as this.double Cube:: { return length_ * length_ * length_; } double Cube:: { return 6 * length_ * length_; }
getVolume
function will return the volume of that cube, for which this function will be called.The
getSurfaceArea
function will return the surface area of that cube, for which this function will be called.
3) Create a custom default constructor to have the initial values for length_
(set it to 1).
public: // you had this code Cube(); //...
Cube::Cube() { length_ = 1; } |
4) Inside the main cpp file create double cube_on_stack()
function to create an object (i.e., a variable) of this class and get volume of it:
double cube_on_stack() { Cube c; c. (2); return c. ; } int main() { // ... }
int main() { cout << "Volume of first cube: " << endl; cube_on_stack(); }
Also, inside the main function create a new cube of length 10 which is going to be in heap memory. Set the values. Print out the information about those objects.
Cube * pcube = new Cube; pcube->setLength(3); cout << "Volume of c cube in the heap memory: " << pcube->getVolume() << endl;
*
) sign. Such objects or instances to the objects can be used together with arrow operator to access their members.5) Create a custom destructor to delete an information about the cube.
~Cube();
Cube::~Cube(){ cout << "Destroyed cube with length " << length_; }
// ... delete pcube;
delete
keyword is used, to reclaim that memory that the object was using. Выполнить: Create a Student
class to output information about the students.
1) The class should contain the following members:
— two data members of type string with private access, they are name
and surname
, and one data member of type int - age
;
— and two member functions with public access:
void set_info(string, string, int);
to set the information about the student
and void get_info(void);
to print out the information.
2) Create a three argument constructor to have the initial values for student.
3) Inside the main cpp file create void student_on_stack()
function to create an object (i.e., a variable) of this class and get volume of it. This object will be in a stack memory. Also, inside the main function create a new student with some info about, which is going to be in a heap memory. Print out the information about those objects.
4) create a custom destructor to delete an information about student.
Пример вывода:
Задание 2: info about student1: name: Johnsurname: Ivanovage: 20 Destructor called for Student Ivanov info about student2: name: Petersurname: Panage: 17 Destructor called for Student Pan
[Solution and Project name: Lesson_10task2
, file name L10Task2main.cpp
, L10Task2imp.cpp
, L10Task2.h
]
Выполнить: Create a BookShop
class to store and output an information about the selling books.
1) The class should contain the following members:
data members with private access:
— title_
(a title of a book) of type string;
— author_
(an author of a book) of type string;
— _price
(a price of a book) of type double;
— _discount
(a discount for a price of a book) of type int.
data members with public access:
- void getInfo()
function to print out the information about the book;
- void set_info(string title, string author, double price, int discount)
function to set the information about the book;
- double getTotalPrice()
function calculate the price of a book considering the discount (price - (price * discount)).
2) Create a four argument constructor to have the initial values for books.
3) Create two objects and print out the information about those objects. Print out the info about the price considering the discount.
Пример вывода:
Задание 3: // book 1 info: Dostoevsky Demons 205 roubles, discount 0.05, total price 194,75 roubles // book 2 info: Kuprin Duel 125 roubles, discount 0.1, total price 112,5 roubles
[Solution and Project name: Lesson_10task3
, file name L10Task3main.cpp
, L10Task3imp.cpp
, L10Task3.h
]
Выполнить:
1) Create a base class called Professor
.
The class should contain the following members:
- Name_
data member of string type with protected access,
- Age_
data member of int type with private access,
- Rating_
data member of int type with protected access,
- Subjects_
data member of list type with private access,
Three member functions with public access:
- void getInfo();
(to output information about a professor),
- void addSubject();
(to add a new subject to the list),
- void checkRating();
(to check a rating and output some message).
2) Create a derived class called ItProfessors
. The class should have its own methods called void MoreInfo();
(to output an addition information) and incRating();
(to increase a rating and output some info).
3) Create a derived class called MathProfessors
. The class should have its own methods called void MoreInfo();
(to output an addition information) and incRating();
(to increase a rating and output some info) .
4) Create an object of the base class inside the main function. Call all existing methods of the class for that object.
5) Create object of the derived classees inside the main function. Call all existing methods of the class.
Пример вывода:
Лабораторная работа 3: name = Ivanov, age =56, subjects = Math name = Johnson, age =50, subjects = Basics_of_programming name = Peterson, age =50, subjects = geometry Ivanov is good in programming name = Petrov, age =45, subjects = IT area professor Johnson's rating was increased and now it is 4 IT area professor Johnson's rating was increased and now it is 5 IT area professor Johnson's rating was increased and now it is 6 Johnson has good rating Ivanov has no enouph good rating
✍ Алгоритм:
- To complete the task you should create a L10lab3.cpp file only. All code should be inside one file.
- Include all the needed libraries:
#include#include<string> #include<list> #include <assert.h> using namespace std;
Create a base class:
class Professor { private: // ... protected: // ... public: // ... };
private
area:int Age_; listSubjects_;
Name_
and Rating_
members must be accessible from the derived class, we should declare them inside the protected
area:string Name_; int Rating_;
public
area. Check the values of passed parameters using assert
statements:Professor(string name, int age, int count) : Name_(name), Age_(age), Rating_(count) { assert(name != ""); assert(age >= 20); assert(age >=0); }
getInfo()
method to output all the information. To output the list we're going to use a for :
loop, iterating over the elements of the list. The method should be inside the public
area:void getInfo() { cout << "name = " << Name_; cout << ", age =" << Age_; cout << ", subjects = "; for (string subj : Subjects_) { cout << subj << " "; } cout << endl; }
push_back()
method:void addSubject(string subject) { Subjects_. (subject); }
Create a derived class:
class ItProfessor:public Professor { public: // ... };
Professor
class. But we need to have public default constructor to have those members accessible outside of this class. Let's add the code of constructor in the public
area:ItProfessor(string name, int age, int count):Professor (name, age, count){ }
public
area as well:void moreInfo(){ cout <" is good in programming" << endl;; }
MathProfessor
:class MathProfessor:public Professor { public: // ... };
MathProfessor(string name, int age, int count):Professor (name, age, count){ }
main
function:ItProfessor IvProfessor("Ivanov", 56,5); ItProfessor JohnProfessor("Johnson", 50, 5); MathProfessor PeterProfessor("Peterson", 50, 5);
IvProfessor.("Math"); IvProfessor. (); JohnProfessor. ("Basics_of_programming"); JohnProfessor. (); PeterProfessor. ("geometry"); PeterProfessor. (); IvProfessor. ();
Professor pr("Petrov", 45, 6); pr.(); // pr. (); error! is not available for the base class
ItProfessor
class:void incRating() { cout << "IT area professor "; Rating_++; cout << Name_ << "'s rating was increased and now it is " << Rating_ << endl; }
MathProfessor
class will be a bit different:void incRating() { cout << " Math area professor "; Rating_++; cout << Name_ << "' rating is " << Rating_ << endl; }
Professor
:void checkRating() { if (Rating_ < 3) { cout << Name_<< " has no enouph good rating" << endl; } else { cout << Name_ << " has good rating" << endl; } }
incRating()
method: JohnProfessor.(); JohnProfessor. (); JohnProfessor. ();
checkRating()
method we should use the pointers. Inside the main function we're going to assign address of the object of the derived class to a pointer of the base class:Professor *p1 = &JohnProfessor; Professor *p2 = &IvProfessor;
p1->checkRating(); p2->checkRating();
1) Create a base class called Animals.
The class should contain the following data members:
-
Name_
data member of string type with protected access,-
Class_
data member of int type with private access (class of vertebrate animal),-
Countries_
data member of List type with private access (countries of residence),-
Population_
data member of int type with private access;The class should contain the following member functions with public access:
-
void getInfo();
(to output information about an animal),-
void addCountry();
(to add a new country to the list and output new list),-
list getAnimalsCountry();
(to return the list of animals by the specified country) .2) Create a derived class called
AfricanAnimals
. Class inherits all the members of Animals class. The class should have its own method called void MoreInfo();
(to output an addition information about African animals).
3) Create an object of the base class inside the main function. Call all existing methods of the class for that object.
4) Create an object of the derived class inside the main function. Call all existing methods of the class.
Note: Create a header file for classes.
Пример вывода:
Задание 4: name = polar_bear сlass = mammal population = 20000 countries = Russia USA Canada what country to add? Greenland new info about countries = Russia USA Canada Greenland name = elephant сlass = mammal population = 20000 countries = Africa India more info about African animals: The fauna of Africa varies greatly depending on the climatic zone. the animals from which country? USA polar_bear
[Solution and Project name: file names L10Task4main.cpp
, L10Task4.h
]