How to overload []= operator?

Hi, guys, I'd like to overload two [] operators in a class, which I can get the set the data. like,

var = test[0];
test[0] = x;

I'd like to know how to realize that. Would anyone help me :)
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
#include <iostream>
#include <stdexcept>

struct my_class
{
    int& operator[] ( std::size_t pos )
    { if( pos < N ) return data[pos] ; else throw std::out_of_range("invalid pos") ; }

    const int& operator[] ( std::size_t pos ) const
    { if( pos < N ) return data[pos] ; else throw std::out_of_range("invalid pos") ; }

    private:
        static constexpr std::size_t N = 5 ;
        int data[N] {} ;
};

int main()
{
    my_class mc ;
    mc[2] = 99 ;

    const my_class another = mc ;
    std::cout << another[2] << '\n' ;

    // another[2] = 99 ; // *** error: const
}
1
2
3
4
5
6
7
8
9
10
11
12
class tilesManage {
	std::vector<cocos2d::Sprite *> tiles;
public:
	tilesManage() {
		tiles = std::vector<cocos2d::Sprite *>(9);
	}
	cocos2d::Sprite * operator[](int n) {
		return tiles[n - 1];
	}
};

tiles[i] = tile;//error 


why in this code, I got a error: left operand must be l-value. The pointer is a modifiable value, but why I got this reminder.
But when I give member function of the following, it works...

1
2
3
void setTile(int n, cocos2d::Sprite *s) {
		tiles[n - 1] = s;
}
What you are doing is the same as 2 = 5;. You are returning a prvalue, a temporary, distinct from original number. You cannot assign anything to it, and even if you could, original value would not be changed.

Look at return type of JLBorges code. It is a reference to value. Any modifications to it will be reflected on original value. So you need a reference to your return type. In your case cocos2d::Sprite*& operator[](int n) { would suffice.
thank you, MiiNiPaa, I see it now.
Topic archived. No new replies allowed.