Simulating offset operator in a c++ class

Feb 11, 2017 at 11:12pm
I have recently learned how to overload operators in c++ classes, but I can't come up with a way to simulate the offset([]) operator. The best I have is returning a pointer to the wanted element, but the * operator has to be used to access the value the pointer points to and I don't want that. The reason why I'm not just returning the value of the element is because then I can't write to the internal array. Basically, I want to be able to make a class c with an internal array of ints (that holds 5 ints), and then access the third int via c[2] so I can do these two things:

a) int temp = c[2];

b) c[2] = 3;

This is my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class test{
public:
    int ar[5] = {1, 2, 3, 4, 5};
    test(){}
    test(int);
    ~test();
    int mes;
    void speak();
    test operator + (test in);
    int *operator [] (int in);
};

int *test::operator [] (int in){
    return (ar + in);
}

test test::operator + (test in){
    test ret = (mes + in.mes);
    return ret;
}

test::test(int in){
    mes = in;
}

void test::speak(){
    std::cout << mes << '\n';
}

test::~test(){
    std::cout << "Closing" << '\n';
}

int main(){
    int in;
    test t, r(10), z(15);
    t = r + z;
    t.speak();
    std::cout << *t[2] << '\n';
    *t[2] = 2;
    std::cout << *t[2] << '\n';
}
Last edited on Feb 11, 2017 at 11:14pm
Feb 11, 2017 at 11:30pm
The best I have is returning a pointer to the wanted element

Return a reference instead.
1
2
      int& operator[](int const in)       noexcept { return arr[in]; }
const int& operator[](int const in) const noexcept { return arr[in]; }

Last edited on Feb 11, 2017 at 11:33pm
Feb 11, 2017 at 11:47pm
Thank you very much, I have to study these tutorials further.
Topic archived. No new replies allowed.