Advertisement
plarmi

workcpp_8_1

Jun 23rd, 2023
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. class Student {
  5. private:
  6.     char* name;
  7.     int age;
  8.  
  9. public:
  10.     // Конструктор по умолчанию
  11.     Student() : name(nullptr), age(0) {}
  12.  
  13.     // Конструктор с параметрами
  14.     Student(const char* n, int a) : age(a) {
  15.         int nameLength = strlen(n);
  16.         name = new char[nameLength + 1];
  17.         strcpy(name, n);
  18.     }
  19.  
  20.     // Конструктор переноса
  21.     Student(Student&& other) : name(other.name), age(other.age) {
  22.         other.name = nullptr;
  23.         other.age = 0;
  24.     }
  25.  
  26.     // Деструктор
  27.     ~Student() {
  28.         delete[] name;
  29.     }
  30.  
  31.     // Геттеры
  32.     const char* getName() const {
  33.         return name;
  34.     }
  35.  
  36.     int getAge() const {
  37.         return age;
  38.     }
  39. };
  40.  
  41. int main() {
  42.     // Создание объекта с помощью конструктора с параметрами
  43.     Student s1("Alice", 20);
  44.     std::cout << "Name: " << s1.getName() << ", Age: " << s1.getAge() << std::endl;
  45.  
  46.     // Создание объекта с помощью конструктора переноса
  47.     Student s2(std::move(s1));
  48.     std::cout << "Name: " << s2.getName() << ", Age: " << s2.getAge() << std::endl;
  49.  
  50.     // Проверка, что объект s1 теперь пустой
  51.     std::cout << "Name: " << (s1.getName() ? s1.getName() : "null") << ", Age: " << s1.getAge() << std::endl;
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement