In article <11**********************@b28g2000cwb.googlegroups .com>,
mu**********@gmail.com says...
hello everybody...
how can i overload the subscript operator with more than one
dimension... like [][][]....
You can't do it directly -- you can either 1) overload some other
operator (most often ()), or 2) you can overload operator[] to return
some type that itself overloads operator[], and so on until you get to
the point of returning the individual item requested.
In the latter category, you have two general possibilities: use
something like std::vector<std::vector<std::vector<double >, or
create multi-dimension matrix class that overloads operator[] to return
a proxy, which overloads operator[] to return a proxy, [to a depth of
dimensions-1], with the final one actually returning the requested item.
// warnings:
// only minimally tested
// no attempt at const correctness
// no attempt at bounds checking
// only supports cube-shaped 3D matrices
//
template<class T, unsigned size>
class matrix3 {
T data[size][size][size];
friend class proxy;
friend class proxy2;
class proxy {
matrix3 &m_;
unsigned index1_, index2_;
public:
proxy(matrix3 &m, unsigned i1, unsigned i2)
: m_(m), index1_(i1), index2_(i2)
{}
T &operator[](unsigned index3) {
return m_.data[index1_][index2_][index3];
}
};
class proxy2 {
matrix3 &m_;
int index_;
public:
proxy2(matrix3 &m, unsigned d) : m_(m), index_(d) { }
proxy operator[](unsigned index2) {
return proxy(m_, index_, index2);
}
};
public:
proxy2 operator[](unsigned index) {
return proxy2(*this, index);
}
};
Used something like:
This code is intended only to demonstrate the basic concept involved --
as theh warnings hint, it's not suitable for serious use as it stands.
#include <iostream>
#include <iomanip>
int main() {
const int size = 4;
matrix3<double, sizem;
for (int x=0; x<size; x++) // initialize the contents
for (int y = 0; y<size; y++)
for (int z = 0; z<size; z++)
m[x][y][z] = x*100 + y * 10 + z;
for (int a=0; a<size; a++) // print out a diagonal
std::cout << std::setw(3)
<< std::setprecision(3)
<< std::setfill('0')
<< m[a][a][a] << "\n";
return 0;
}
--
Later,
Jerry.
The universe is a figment of its own imagination.