Advertisement
Mihai_Preda

Untitled

Mar 11th, 2021
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5.  
  6. // ELEMENTE ALOCATE DINAMIC IN CLASA => COPY CONSTRUCTOR
  7. class Vector
  8. {
  9. private:
  10.     int *v;
  11.     int n;
  12. public:
  13.     Vector(int n)
  14.     {
  15.         this->n = n;
  16.         v = new int[n];
  17.     }
  18.     Vector(const Vector& other)
  19.     {
  20.         cout << "Copy constructor\n";
  21.         n = other.n;
  22.         v = new int[n];
  23.         for(int i = 0; i < n; i++)
  24.         v[i] = other.v[i];
  25.     }
  26.     ~Vector()
  27.     {
  28.         delete[] v;
  29.     };
  30.     void setElement(int ind, int val)
  31.     {
  32.         v[ind] = val;
  33.     }
  34.     int getElement(int ind)
  35.     {
  36.         return v[ind];
  37.     }
  38.     int catePare()
  39.     {
  40.        int cnt = 0;
  41.        for(int i = 0; i < n; i++)
  42.             if(v[i] % 2 == 0)
  43.                 cnt++;
  44.        return cnt;
  45.     }
  46.     void operator*=(int x)
  47.     {
  48.         for(int i = 0; i < n; i++)
  49.             v[i] += x;
  50.     }
  51.     int& operator[](int x)
  52.     {
  53.         return v[x];
  54.     }
  55.     void operator=(const Vector& other)
  56.     {
  57.         cout << "operator=\n";
  58.         delete[] v;
  59.         n = other.n;
  60.         v = new int[n];
  61.         for(int i = 0; i < n; i++)
  62.         v[i] = other.v[i];
  63.     }
  64. };
  65.  
  66.  
  67. int main()
  68. {
  69.     Vector * a = new Vector(5);
  70.     a->setElement(3, 12);
  71.     cout << a->getElement(3);
  72.  
  73.     delete a;
  74.     return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement