Введение
В этом практическом занятии вы научитесь реализовывать концепцию класса и его членов в программировании на C++. Класс - это пользовательский тип данных, который служит чертежом для объектов. Члены класса могут быть переменными или функциями, и их можно определить как публичные, приватные или защищенные.
Создайте и отредактируйте главный исходный файл
Во - первых, нам нужно создать и отредактировать главный исходный файл. Откройте терминал и перейдите в директорию проекта с помощью команды cd:
cd ~/project
Создайте и откройте главный исходный файл:
touch main.cpp
Добавьте в файл следующий код:
#include <iostream>
using namespace std;
class LabEx {
private:
int value;
public:
void input() {
cout << "Entering the input() function\n";
cout << "Enter an integer you want to display: ";
cin >> value;
cout << "Exiting the input() function\n\n";
}
void display() {
cout << "\nEntering the display() function\n";
cout << "The value entered is: " << value << endl;
cout << "Exiting the display() function\n\n";
}
};
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the concept of Class, in CPP ===== \n\n";
LabEx object;
cout << "\n\nCalling the input() function from the main() method\n\n\n";
object.input();
cout << "\nCalling the display() function from the main() method\n\n\n";
object.display();
cout << "\n\nExiting the main() method\n\n\n";
return 0;
}
В коде определен класс LabEx с двумя член - функциями input() и display(). Функция input() принимает ввод от пользователя и сохраняет его в value, а функция display() выводит сохраненное значение на экран.
Скомпилируйте и запустите программу
Скомпилируйте программу, выполнив следующую команду в терминале:
g++ main.cpp -o main && ./main
При успешной компиляции и выполнении вы должны увидеть следующий вывод:
Welcome to LabEx :-)
===== Program to demonstrate the concept of Class, in CPP =====
Calling the input() function from the main() method
Entering the input() function
Enter an integer you want to display: 5
Exiting the input() function
Calling the display() function from the main() method
Entering the display() function
The value entered is: 5
Exiting the display() function
Exiting the main() method
Резюме
В этом практическом занятии вы узнали, как определить класс и его члены, как объявить и инициализировать объекты класса, и как обращаться к членам класса с использованием конструктора.
Теперь вы можете использовать концепцию класса и его членов на C++ для написания более сложных программ, требующих пользовательских типов данных. Эта концепция также может помочь вам достичь лучшей организации кода и улучшить читаемость, применяя методы объектно - ориентированного программирования (OOP).
Полный код
Не забудьте изменить путь и имя файла в соответствии с вашей реализацией.
#include <iostream>
using namespace std;
class LabEx {
private:
int value;
public:
void input() {
cout << "Entering the input() function\n";
cout << "Enter an integer you want to display: ";
cin >> value;
cout << "Exiting the input() function\n\n";
}
void display() {
cout << "\nEntering the display() function\n";
cout << "The value entered is: " << value << endl;
cout << "Exiting the display() function\n\n";
}
};
int main() {
cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " ===== Program to demonstrate the concept of Class, in CPP ===== \n\n";
LabEx object;
cout << "\n\nCalling the input() function from the main() method\n\n\n";
object.input();
cout << "\nCalling the display() function from the main() method\n\n\n";
object.display();
cout << "\n\nExiting the main() method\n\n\n";
return 0;
}



