image.png

    1. #include <iostream>
    2. #include <cstring>
    3. using namespace std;
    4. class Array2
    5. {
    6. public:
    7. Array2(int m_, int n_) : m(m_), n(n_)
    8. {
    9. arr = new int *[m_];
    10. for (int i = 0; i < m_; ++i)
    11. arr[i] = new int[n_];
    12. }
    13. Array2() : m(0), n(0)
    14. {
    15. arr = NULL;
    16. }
    17. Array2 &operator=(const Array2 &a)
    18. {
    19. if (this == &a)
    20. return *this;
    21. m = a.m;
    22. n = a.n;
    23. if (arr)
    24. {
    25. for (int i = 0; i < m; ++i)
    26. delete[] arr[i];
    27. delete[] arr;
    28. }
    29. if (a.arr)
    30. {
    31. arr = new int *[m];
    32. for (int i = 0; i < m; ++i)
    33. arr[i] = new int[n];
    34. for (int i = 0; i < m; ++i)
    35. for (int j = 0; j < n; ++j)
    36. arr[i][j] = a.arr[i][j];
    37. }
    38. else
    39. arr = NULL;
    40. return *this;
    41. }
    42. ~Array2()
    43. {
    44. if (arr)
    45. {
    46. for (int i = 0; i < m; ++i)
    47. delete[] arr[i];
    48. delete[] arr;
    49. arr = NULL;
    50. }
    51. }
    52. int *operator[](int m)
    53. {
    54. return arr[m];
    55. }
    56. int &operator()(int i, int j)
    57. {
    58. return arr[i][j];
    59. }
    60. int **arr;
    61. int m, n;
    62. };
    63. int main()
    64. {
    65. Array2 a(3, 4);
    66. int i, j;
    67. for (i = 0; i < 3; ++i)
    68. for (j = 0; j < 4; j++)
    69. a[i][j] = i * 4 + j;
    70. for (i = 0; i < 3; ++i)
    71. {
    72. for (j = 0; j < 4; j++)
    73. {
    74. cout << a(i, j) << ",";
    75. }
    76. cout << endl;
    77. }
    78. cout << "next" << endl;
    79. Array2 b;
    80. b = a;
    81. for (i = 0; i < 3; ++i)
    82. {
    83. for (j = 0; j < 4; j++)
    84. {
    85. cout << b[i][j] << ",";
    86. }
    87. cout << endl;
    88. }
    89. return 0;
    90. }
    • 主要考察”()”和”[]”运算符的重载,同时考察了二维数组指针的动态申请和拷贝等操作
      • 关注“()”和“[]”运算符的重载
      • 注意二维数组的申请,申请第二维的时候是for(i=0; i < m; ++i),不是for(i=0; i < n; ++i)