Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

97 lignes
1.8KB

  1. template <class T> class Array {
  2. public:
  3. typedef T MemberType; // Merke Grundtyp
  4. // Iterator fuer die Feld-Klasse
  5. class Iterator {
  6. private:
  7. T* p; // Iterator ist ein Zeiger ...
  8. Iterator(T* q) {p=q;}
  9. public:
  10. Iterator() {p=0;}
  11. bool operator!= (Iterator x) {
  12. return (p!=x.p);
  13. }
  14. bool operator== (Iterator x) {
  15. return (p==x.p);
  16. }
  17. Iterator operator++ () {
  18. p++;
  19. return *this;
  20. }
  21. Iterator operator++ (int) {
  22. Iterator tmp = *this;
  23. ++*this;
  24. return tmp;
  25. }
  26. T& operator* () const {return *p;}
  27. T* operator-> () const {return p;}
  28. friend class Array<T>;
  29. } ;
  30. // Iterator Methoden
  31. Iterator begin () const {
  32. return Iterator(p);
  33. }
  34. Iterator end () const {
  35. return Iterator(&(p[n])); // ja, das ist ok!
  36. }
  37. // Konstruktion; Destruktion und Zuweisung
  38. Array(int m) {
  39. n = m;
  40. p = new T[n];
  41. }
  42. Array (const Array<T>&);
  43. Array<T>& operator= (const Array<T>&);
  44. ~Array() {
  45. delete[] p;
  46. }
  47. // Array manipulation
  48. int size () const {
  49. return n;
  50. }
  51. T& operator[](int i) {
  52. return p[i];
  53. }
  54. private:
  55. int n; // Anzahl Elemente
  56. T *p; // Zeiger auf built-in array
  57. } ;
  58. // Copy-Konstruktor
  59. template <class T>
  60. Array<T>::Array (const Array<T>& a) {
  61. n = a.n;
  62. p = new T[n];
  63. for (int i=0; i<n; i=i+1)
  64. p[i]=a.p[i];
  65. }
  66. // Zuweisung
  67. template <class T>
  68. Array<T>& Array<T>::operator= (const Array<T>& a) {
  69. if (&a!=this) {
  70. if (n!=a.n) {
  71. delete[] p;
  72. n = a.n;
  73. p = new T[n];
  74. }
  75. for (int i=0; i<n; i=i+1) p[i]=a.p[i];
  76. }
  77. return *this;
  78. }
  79. // Ausgabe
  80. template <class T>
  81. std::ostream& operator<< (std::ostream& s, Array<T>& a) {
  82. s << "array " << a.size() <<
  83. " elements = [" << std::endl;
  84. for (int i=0; i<a.size(); i++)
  85. s << " " << i << " " << a[i] << std::endl;
  86. s << "]" << std::endl;
  87. return s;
  88. }