int& operator[](int idx)class BoundCheckIntArray{
private:
int * arr;
int arrlen;
BoundCheckIntArray(const BoundCheckIntArray& arr) {}
BoundCheckIntArray& operator=(const BoundCheckIntArray& arr) {}
public:
BoundCheckIntArray(int len) : arrlen(len){
arr = new int[len];
}
int& operator[] (int idx){
if(idx<0 || idx>=arrlen){
cout<<"Array index out of bound exception"<<endl;
exit(1);
}
return arr[idx];
}
int GetArrLen() const { return arrlen; }
~BoundCheckIntArray() { delete[] arr; }
};
void ShowAllData(const BoundCheckIntArray& ref){
int len = ref.GetArrLen();
for(int idx = 0 ; idx<len ; idx++){
cout<<ref[idx]<<endl;
}
}
int main(){
BoundCheckIntArray arr(5);
for(int i = 0 ; i < 5 ; i++){
arr[i] = (i+1)*11;
}
ShowAllData(arr);
return 0;
}
void ShowAllData(const BoundCheckIntArray& ref){
int len = ref.GetArrLen();
for(int idx = 0 ; idx<len ; idx++){
cout<<ref[idx]<<endl;
}
}
BoundCheckIntArray가 const로 전달되어 수정을 막고 있다.operator= 연산자 오버로딩 함수는 const 함수가 아니기 때문에 컴파일 오류를 발생시킴.⚠️ 인자가 const로 들어오면, const함수가 아닌 모든 함수를 사용할 수 없음에 유의
해결방안
operator= 연산자 오버로딩 함수를 const인것 하나, 아닌것 하나로 오버로딩한다.#include <iostream>
#include <cstdlib>
using namespace std;
class BoundCheckIntArray{
private:
int * arr;
int arrlen;
BoundCheckIntArray(const BoundCheckIntArray& arr) {}
BoundCheckIntArray& operator=(const BoundCheckIntArray& arr) {}
public:
BoundCheckIntArray(int len) : arrlen(len){
arr = new int[len];
}
/*
* 수정된 부분 시작------------------------------
*/
int& operator[] (int idx){
if(idx<0 || idx>=arrlen){
cout<<"Array index out of bound exception"<<endl;
exit(1);
}
return arr[idx];
}
int& operator[] (int idx) const{
if(idx<0 || idx>=arrlen){
cout<<"Array index out of bound exception"<<endl;
exit(1);
}
return arr[idx];
}
/*
* 수정된 부분 끝--------------------------------
*/
int GetArrLen() const { return arrlen; }
~BoundCheckIntArray() { delete[] arr; }
};
void ShowAllData(const BoundCheckIntArray& ref){
int len = ref.GetArrLen();
for(int idx = 0 ; idx<len ; idx++){
cout<<ref[idx]<<endl;
}
}
int main(){
BoundCheckIntArray arr(5);
for(int i = 0 ; i < 5 ; i++){
arr[i] = (i+1)*11;
}
ShowAllData(arr);
return 0;
}