BeloMaximka

Belov_HW_O13

Sep 21st, 2021 (edited)
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #pragma once
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. template <class T>
  6. class MyVector
  7. {
  8.     T* ptr;
  9.     int size;
  10.     static int count; //колво векторов
  11.     friend ostream& operator<<<>(ostream& os, MyVector<T>& obj);
  12.     friend istream& operator>><>(istream& is, MyVector<T>& obj);
  13. public:
  14.     MyVector(); //0
  15.     MyVector(int size);
  16.     MyVector(const MyVector& obj);
  17.     ~MyVector();
  18.     T& operator=(const T& obj);
  19.     T& operator[](int index);
  20.     static int getCount();
  21. };
  22.  
  23. template <class T>
  24. int MyVector<T>::count = 0;
  25.  
  26. template <class T>
  27. ostream& operator<<(ostream& os, MyVector<T>& obj);
  28.  
  29. template <class T>
  30. istream& operator>>(istream& is, MyVector<T>& obj);
  31.  
  32. template<class T>
  33. inline MyVector<T>::MyVector()
  34. {
  35.     size = 0;
  36.     ptr = nullptr;
  37.     count++;
  38. }
  39.  
  40. template<class T>
  41. inline MyVector<T>::MyVector(int size)
  42. {
  43.     this->size = size;
  44.     ptr = new T[size];
  45.     count++;
  46. }
  47.  
  48. template<class T>
  49. inline MyVector<T>::MyVector(const MyVector& obj)
  50. {
  51.     size = obj.size;
  52.     ptr = new T[size];
  53.     for (int i = 0; i < size; i++) ptr[i] = obj.ptr[i];
  54.     count++;
  55. }
  56.  
  57. template<class T>
  58. inline MyVector<T>::~MyVector()
  59. {
  60.     delete[] ptr;
  61. }
  62.  
  63. template<class T>
  64. inline T& MyVector<T>::operator=(const T& obj)
  65. {
  66.     if (this == &obj) return *this;
  67.  
  68.     if (ptr != nullptr) delete[] ptr;
  69.     size = obj.size;
  70.  
  71.     ptr = new T[size];
  72.     for (int i = 0; i < size; i++) ptr[i] = obj.ptr[i];
  73.  
  74.     return *this;
  75. }
  76.  
  77. template<class T>
  78. inline T& MyVector<T>::operator[](int index)
  79. {
  80.     return ptr[index];
  81. }
  82.  
  83. template<class T>
  84. inline int MyVector<T>::getCount()
  85. {
  86.     return count;
  87. }
  88.  
  89. template<class T>
  90. inline ostream& operator<<(ostream& os, MyVector<T>& obj)
  91. {
  92.     for (int i = 0; i < obj.size; i++)
  93.     {
  94.         os << obj.ptr[i] << ", ";
  95.     }
  96.     os << "\b\b ";
  97.     return os;
  98. }
  99.  
  100. template<class T>
  101. inline istream& operator>>(istream& is, MyVector<T>& obj)
  102. {
  103.     for (int i = 0; i < obj.size; i++)
  104.     {
  105.         cout << i + 1 << " element: ";
  106.         is >> obj.ptr[i];
  107.     }
  108.     return is;
  109. }
Add Comment
Please, Sign In to add comment