Programming/C++
[Programming/C++] 2차원 배열접근에 대한 연산자 오버로딩의 예
scii
2021. 2. 5. 11:31
#include <iostream>
#include <cstdlib>
#pragma warning(disable: 4996)
using std::cout;
using std::cin;
using std::endl;
class BoundCheckIntArray {
private:
int* arr;
int arrlen;
explicit BoundCheckIntArray(const BoundCheckIntArray& ref) {}
BoundCheckIntArray& operator=(const BoundCheckIntArray& ref) {}
public:
explicit BoundCheckIntArray(int len) : arrlen(len) {
arr = new int[len];
}
~BoundCheckIntArray() {
delete[] arr;
}
int& operator[](const int idx) {
if (idx < 0 || idx >= arrlen) {
cout << "범위를 벗어남..." << endl;
exit(1);
}
return arr[idx];
}
int operator[](const int idx) const {
if (idx < 0 || idx >= arrlen) {
cout << "범위를 벗어남..." << endl;
exit(1);
}
return arr[idx];
}
};
typedef BoundCheckIntArray* BoundCheckIntArrayPtr;
class BoundCheck2DIntArray {
private:
int row, col;
BoundCheckIntArrayPtr* arr;
explicit BoundCheck2DIntArray(const BoundCheck2DIntArray& ref) {}
BoundCheck2DIntArray& operator=(const BoundCheck2DIntArray& ref) {}
public:
explicit BoundCheck2DIntArray(const int row, const int col) : row(row), col(col) {
arr = new BoundCheckIntArrayPtr[row];
for (int i = 0; i < row; i++) {
arr[i] = new BoundCheckIntArray(col);
}
}
~BoundCheck2DIntArray() {
delete[] arr;
}
BoundCheckIntArray& operator[](const int idx) {
if (idx < 0 || idx >= row) {
cout << "범위를 벗어남..." << endl;
exit(1);
}
return *(arr[idx]);
}
};
int main(const int argc, const char* const argv[]) {
BoundCheck2DIntArray arr2d(3, 4);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
arr2d[i][j] = i + j;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
cout << arr2d[i][j] << ' ';
}
cout << endl;
}
return 0;
}
/* 결과
0 1 2 3
1 2 3 4
2 3 4 5
*/
두 번의 [ ] 연산자 호출을 동반하게끔 구현해야 한다. 즉, 다음과 같이 해석되어야 하며
(arr2d.operator[](i))[j];
그리고 arr2d.operator[](i) 연산의 반환 값을 이용해서 두 번째 [ ] 연산을 다음과 같이 해석되어야 한다.
((반환 값).operator[])(j);