operator[][](const int i, const int j)
Hello gurus,
I am developing a two-dimensional matrix template class and I need help with a syntax problem.
It is common to write the operator[](const int n) for one-dimensional data arrays.
Is it possible to write the operator[][](const int i, const int j) for two-dimensional data arrays? If so, then what is the proper syntax. Maybe someone can work it into my sample code.
Here is a slimmed down version of the code in question in case anyone really wants to get into this one and help me out.
Thanks for any help.
Chris.
Code:
#include <iostream>
template<typename T> class c_matrix
{
private:
T** data;
const int nrow;
const int ncol;
bool valid;
public:
c_matrix(const int nr, const int nc) : nrow(nr), ncol(nc)
{
valid = true;
data = new(std::nothrow) T*[nrow];
if(data == NULL)
{
valid = false;
return;
}
register int i;
for(i = 0; i < nrow; i++)
{
data[i] = new(std::nothrow) T[ncol];
if(data[i] == NULL)
{
valid = false;
return;
}
}
}
~c_matrix()
{
if(valid)
{
int i;
for(i = 0; i < nrow; i++)
{
delete [] data[i];
}
delete [] data;
}
}
public:
// I would like to write operator[][](const int i, const int j) if possible
const void set(const int i, const int j, const T& value)
{
if(valid)
{
data[i][j] = value;
}
}
const T& get(const int i, const int j) const
{
if(valid)
{
return data[i][j];
}
else
{
static const T zero = 0;
return zero;
}
}
const int row(void) const { return ncol; }
const int col(void) const { return nrow; }
};
template<typename T>
inline ::std::ostream& operator<<(::std::ostream& os, const c_matrix<T>& m)
{
register int i;
for(i = 0; i < m.row(); i++)
{
register int j;
for(j = 0; j < m.col(); j++)
{
os << m.get(i, j) << '\t';
}
if(i != m.row() - 1 && j != m.col() - 1)
{
os << std::endl;
}
}
return os;
}
int main(int argc, char* argv[])
{
c_matrix<double> m(3, 3);
// I would like to write m[0][0] = +1
m.set(0, 0, +1);
m.set(0, 1, +2);
m.set(0, 2, +3);
m.set(1, 0, -1);
m.set(1, 1, +2);
m.set(1, 2, 0);
m.set(2, 0, +7);
m.set(2, 1, +6);
m.set(2, 2, -2);
std::cout << m << std::endl;
return 1;
}