fork download
  1. #include <algorithm>
  2. #include <cassert>
  3.  
  4. template<typename T> class Array2D
  5. {
  6. public:
  7. Array2D(size_t width, size_t height)
  8. : width(width)
  9. , height(height)
  10. , p_data(new T[width * height])
  11. {
  12. }
  13.  
  14. Array2D(const Array2D& other)
  15. : width(other.width)
  16. , height(other.height)
  17. , p_data(new T[other.width * other.height])
  18. {
  19. *this = other;
  20. }
  21.  
  22. ~Array2D()
  23. {
  24. delete[] p_data;
  25. }
  26.  
  27. // Zugriffsoperator
  28. T& operator()(size_t x, size_t y)
  29. {
  30. assert(x < width && y < height);
  31. return p_data[y * width + x];
  32. }
  33.  
  34. // Zugriffsoperator (const)
  35. const T& operator()(size_t x, size_t y) const
  36. {
  37. assert(x < width && y < height);
  38. return p_data[y * width + x];
  39. }
  40.  
  41. // Zuweisungsoperator
  42. Array2D& operator =(const Array2D& rhs)
  43. {
  44. assert(width == rhs.width && height == rhs.height);
  45.  
  46. // Daten kopieren
  47. std::copy(rhs.p_data, rhs.p_data + width * height, p_data);
  48.  
  49. return *this;
  50. }
  51.  
  52. // Getter
  53. size_t getWidth() const { return width; }
  54. size_t getHeight() const { return height; }
  55.  
  56. private:
  57. const size_t width;
  58. const size_t height;
  59. T* const p_data;
  60. };
  61.  
  62. int main()
  63. {
  64. // Beispiel für Benutzung:
  65. Array2D<int> meinArray(30, 50);
  66. meinArray(10, 10) = 42;
  67. meinArray(1000, 1000) = 0; // <-- Fehler, wird bei Debug vom "assert" abgefangen
  68. }
Runtime error #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
Standard output is empty