#include <iostream>
usingnamespace std;
struct mat
{
double arr[64];// for example
int cols;// length of each row
double* operator[](int r){ return arr + r*cols; }// overload []
// ctor provides easy initialization for this example
mat(int Cols): cols(Cols)
{
for(int i=0; i<64; ++i)
arr[i] = i;
}
};
int main()
{
mat m(8);// sets m up with 8 doubles per row
cout << m[4][3] << endl;// outputs 35 = 4*8+3 - works as rvalue
m[5][2] = 8.5;// test for use as an lvalue
cout << m[5][2] << endl;// gives 8.5 so lvalue test is good.
return 0;
}
If you're going to the trouble of writing an ADT for your matrix, I'd consider going a bit further and, rather than return a double*, use a helper class so you can control access to the elements.
The nested row class is a kind of range-checking replacement for the double* pointer.
out_of_range is the same exception throw by vector::at() when you try to use an invalid index. if throwing an exception seems a bit heavy handed, it could be replaced with an assertion in the debug build.