fork download
  1. #include <iostream>
  2.  
  3. ///define a matrix class
  4. ///this is a large object that can hold big memory
  5. class matrix
  6. {
  7. int rows;
  8. int cols;
  9. double **mat;
  10.  
  11. public:
  12.  
  13. matrix( )
  14. {
  15. //default constructor
  16. rows = cols = 0;
  17. mat = 0;
  18. };
  19.  
  20. //constructor
  21. matrix( int r, int c )
  22. {
  23. std::cout << "ctor called\n";
  24. rows = r;
  25. cols = c;
  26. mat = new double* [ r ];
  27. for( int i = 0; i < r; ++i )
  28. mat[ i ] = new double [ c ];
  29. };
  30.  
  31. //copy constructor -- method for initializing one matrix directly from another
  32. matrix( const matrix& other)
  33. {
  34. std::cout << "copy ctor called\n";
  35. rows = other.rows;
  36. cols = other.cols;
  37. mat = new double* [rows];
  38. for( int i = 0; i < rows; ++i )
  39. {
  40. mat[i] = new double [ cols ];
  41. for( int j = 0; j < cols; ++j )
  42. mat[i][j] = other.mat[i][j];
  43. }
  44. };
  45.  
  46. //destructor
  47. ~matrix( )
  48. {
  49. std::cout << "dtor called\n";
  50. for( int i = 0 ; i < rows; ++i )
  51. if( mat[i] ) delete [] mat[i];
  52. if( mat ) delete [] mat;
  53. mat = 0;
  54. };
  55.  
  56. ///overload operator +
  57. matrix operator+( const matrix &other )
  58. {
  59. std::cout << "op+ called\n";
  60. matrix m(other.rows, other.cols);
  61. for( int i = 0; i < other.rows; i++ )
  62. for( int j = 0; j < other.cols; j++ )
  63. m.mat[i][j] = mat[i][j] + other.mat[i][j];
  64. return m;
  65. };
  66.  
  67. //get a matrix element
  68. double &element(int i, int j) { return mat[i][j]; }
  69.  
  70. };
  71.  
  72.  
  73.  
  74. int main( )
  75. {
  76. ///initialize matrices -- bug dense matrices
  77. matrix M1(1000,1000), M2(1000,1000);
  78.  
  79. for( int i = 0; i < 1000; ++i )
  80. {
  81. for( int j = 0; j < 1000; ++j )
  82. {
  83. M1.element(i,j) = 1;
  84. M2.element(i,j) = 2;
  85. }
  86. }
  87.  
  88.  
  89. ///DO the following!
  90. matrix M3 = M1 + M2;
  91. std::cout << M3.element(500,500) << '\n';
  92. }
  93.  
Success #stdin #stdout 0.04s 2856KB
stdin
Standard input is empty
stdout
ctor called
ctor called
op+ called
ctor called
3
dtor called
dtor called
dtor called