fork download
  1. #include <cstring>
  2. #include <iostream>
  3.  
  4. using std::size_t;
  5.  
  6. class Mesh2D
  7. {
  8. private:
  9.  
  10. double* mesh;
  11. size_t rows;
  12. size_t columns;
  13.  
  14. public:
  15.  
  16. /* constructor */
  17. Mesh2D(size_t Nx, size_t Ny){
  18. rows = Nx;
  19. columns = Ny;
  20. mesh = new double[Nx*Ny] {};
  21. std::cout << "Mesh created." << std::endl;
  22. }
  23.  
  24. /* destructor */
  25. ~Mesh2D()
  26. {
  27. delete[] mesh;
  28. std::cout << "Mesh deleted." << std::endl;
  29. }
  30.  
  31. /* accessors */
  32. double getrows() const {return rows;}
  33. double getcolumns() const {return columns;}
  34. double& operator()(size_t i, size_t j)
  35. {
  36. if (i > rows || j > columns){
  37. throw std::out_of_range("Index exceeds array bounds.");
  38. }
  39. return mesh[j + i*columns]; // row major access
  40. }
  41.  
  42. double operator()(size_t i, size_t j) const
  43. {
  44. if (i > rows || j > columns){
  45. throw std::out_of_range("Index exceeds array bounds.");
  46. }
  47. return mesh[j + i*columns]; // row major access
  48. }
  49.  
  50. /* copy constructor */
  51. Mesh2D& operator=(const Mesh2D& rhs) // what is the difference between this line and the following? inline operator=(const Mesh2D& rhs)
  52. {
  53. if (rhs.rows != rows || rhs.columns != columns){
  54. throw std::out_of_range("Assignment cannot be performed, mesh dimensions do not agree.");
  55. }
  56. if (&rhs == this) //copying the same object
  57. return *this;
  58.  
  59. // I want to avoid using a for loop
  60. // for (int i=0; i<rows*columns; i++){
  61. // mesh[i] = rhs.mesh[i];
  62. // }
  63. // Use this instead
  64. std::memcpy(mesh, rhs.mesh, rows*columns * sizeof(double)); //however the output is not the expected.
  65. std::cout << "copied!" << std::endl;
  66. return *this;
  67. }
  68.  
  69. };
  70.  
  71.  
  72.  
  73. void PrintMesh2D(const Mesh2D &mesh){ //why isn't it going to work if I add const? I mean: void PrintMesh2D(const Mesh2D &mesh)
  74.  
  75. for (int i=0; i<mesh.getrows(); i++){
  76.  
  77. for (int j=0; j<mesh.getcolumns(); j++){
  78.  
  79. std::cout << mesh(i,j) << " ";
  80. }
  81. std::cout << std::endl;
  82. }
  83. }
  84.  
  85. int main()
  86. {
  87.  
  88. Mesh2D mesh{3,3};
  89. Mesh2D newmesh{3,3};
  90.  
  91. for (int i=0; i<mesh.getrows(); i++){
  92. for (int j=0; j<mesh.getcolumns(); j++){
  93. mesh(i,j) = j + i * mesh.getcolumns();
  94. }
  95. }
  96.  
  97. newmesh = mesh;
  98. PrintMesh2D(newmesh);
  99.  
  100. }
Success #stdin #stdout 0s 4452KB
stdin
Standard input is empty
stdout
Mesh created.
Mesh created.
copied!
0 1 2 
3 4 5 
6 7 8 
Mesh deleted.
Mesh deleted.