Advertisement
frentzy

clasa template exemplu

Jun 12th, 2018
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #pragma warning(disable:4996)
  2. #include <iostream>
  3. #include <conio.h>
  4. #include <stdio.h>
  5. using namespace std;
  6. #define MAX 2435
  7. template <class T>
  8. class Vector {
  9. private:
  10.     T elem[MAX];
  11.     int n;
  12. public:
  13.     Vector(int n);
  14.     int getNrElemente() const;
  15.     T& operator[] (int i);
  16.     int & operator +(int i) {
  17.         int suma = 0;
  18.         this->elem[0] += i;
  19.         return this->elem[0];
  20.     }
  21.     void print();
  22. };
  23. template <class T>
  24. Vector<T>::Vector<T>(int n) {
  25.     this->n = n;
  26.     if (n>MAX)
  27.         throw out_of_range("Depasire dimensiune maxima");
  28.     else {
  29.         for (int i = 0; i < n; i++) {
  30.             this->elem[i] = 0;
  31.         }
  32.     }
  33. }
  34.  
  35. template <class T>
  36. int Vector<T>::getNrElemente() const {
  37.     return n;
  38. }
  39. template <class T>
  40. T& Vector<T>:: operator[] (int i) {
  41.     if (i >= 0 && i < n) {
  42.         return elem[i];
  43.     }
  44.     else {
  45.         throw out_of_range("Depasire limite");
  46.     }
  47. }
  48. template <class T>
  49. void Vector<T>::print() {
  50.     int i;
  51.     for (i = 0; i < n; i++) {
  52.         cout << elem[i] << " ";
  53.     }
  54.     cout << endl;
  55. }
  56. void main() {
  57.     Vector<int> frentzy(2);
  58.     frentzy.print();
  59.     int cacat = frentzy + 3;
  60.     frentzy.print();
  61.    
  62.  
  63.     _getch();
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement