Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload operator[] in std::array

I would like to optimize my code overloading the bracket [ ] operator in std::array, which I use everywhere subtracting one. The code compiles but never calls the overloaded function, could anyone tell me why?

#include <iostream>
#include <array>
class A
{
    std::array<int,5> var{0, 1, 2, 3, 4};
    std::array<int, 5ul>::value_type& operator[](std::size_t p_index);
};

std::array<int, 5ul>::value_type& A::operator[](std::size_t p_index)
{
    return var[p_index - 1];
}

int main()
{
    A a;
    std::cout << a.var[1] << std::endl;
}

Code returns "1" but I would expect "0". Thanks in advance!

like image 949
Victor Avatar asked Jan 01 '23 11:01

Victor


1 Answers

You are not "overloading" subscription operator [] for your array; you are rather defining your own subscription operator for class A, which will be invoked on instances of A, but not on instances of A's data member var.

So you need to write...

std::cout << a[1] << std::endl;

Output:

0
like image 167
Stephan Lechner Avatar answered Jan 07 '23 22:01

Stephan Lechner