I was making my own bound-checking array class, but I got a problem that it is unable to call the appropriate overloaded function when using the operator [].
The first overloaded operator []
is for getting an actual value(=content) of the array instance: such an instructionnum1 = list1[2]
to be possible.
The second overloaded operator []
is for assigning the given rvalue to the MyArrayList
.
But when running main
function, it was unable to call the second one. the whole code is like this:
#include <iostream>
template <typename Data>
class MyArrayList {
private :
Data* data_storage;
int num_of_elements;
int array_size;
int idx_cursor;
public :
MyArrayList(int _size);
void add_element(Data new_data);
void remove_element();
Data operator[](int idx) const;
MyArrayList& operator[](int idx);
void operator=(Data new_data);
~MyArrayList();
};
template <typename Data>
MyArrayList<Data>::MyArrayList(int _size) {
array_size = _size;
data_storage = new Data[array_size];
num_of_elements = 0;
idx_cursor = 0;
}
template <typename Data>
void MyArrayList<Data>::add_element(Data new_data) {
if(num_of_elements > array_size) {
std::cout << "Unable to store more." << std::endl;
return;
}
data_storage[++num_of_elements - 1] = new_data;
}
template <typename Data>
void MyArrayList<Data>::remove_element() {
if(num_of_elements <= 0) {
std::cout << "Unable to delete anymore" << std::endl;
return;
}
Data* temp = data_storage;
delete[] data_storage;
data_storage = new Data[--num_of_elements];
for(int i = 0; i < num_of_elements; i++)
data_storage[i] = temp[i];
delete[] temp;
}
template <typename Data>
MyArrayList<Data>::~MyArrayList() {
delete[] data_storage;
}
template <typename Data>
Data MyArrayList<Data>::operator[](int idx) const { //var = list1[5];
if(idx < 0) {
int new_idx = idx;
while(new_idx < 0) {
std::cout << "IndexOutofBounds! Enter new index." << std::endl;
std::cin >> new_idx; std::cout << std::endl;
new_idx--;
}
idx = new_idx;
}
return data_storage[idx];
}
template <typename Data>
MyArrayList<Data>& MyArrayList<Data>::operator[](int idx){ // list1[2] = 5;
idx_cursor = idx;
return *this;
}
template <typename Data>
void MyArrayList<Data>::operator=(Data new_data){
data_storage[idx_cursor] = new_data;
}
int main() {
int num1;
MyArrayList<int> list1(5);
list1.add_element(6);
list1.add_element(7);
list1.add_element(8);
list1.add_element(9);
list1[2] = 5; //possible
//std::cout << num1 << std::endl; //not possible. probably not calling the first overloaded operator[]()?
}
I first tried to rewrite the second overloaded operator[]()
with using friend
keyword, but in the second guess, I thought it was not a good idea, and there's no way coming up with to solve the problem.