Martin Dvoracek
Martin Dvoracek

Reputation: 1738

How to recognize the assignment operator?

I've got class with overloaded [] and I need to make it to recognize, when I try to set the values to the array. I assume, that I'll have to overload the operator =, nevertheless I don't know, how shall that whole stuff look like. Part of my code:

class Matrix {
public:

Matrix(int x, int y);
~Matrix(void);
Matrix& operator =(const Matrix &matrix); //ok...this is probably wrong...

class Proxy {
public:

    Proxy(double* _array) : _array(_array) {
    }

    double &operator[](int index) const {
        return _array[index];
    }

private:
    double* _array;
};

Proxy operator[](int index) const {
    return Proxy(_arrayofarrays[index]);
}

Proxy operator[](int index) {
    return Proxy(_arrayofarrays[index]);
}

int x, y;
double** _arrayofarrays;
};

So I just need to be able to recognize when I try to set Matrix matrix(3,3); matrix[0][0]=1; Everything else works allright, so I assumed that it's not needed to paste the whole code

Upvotes: 0

Views: 182

Answers (2)

optikradio
optikradio

Reputation: 81

It looks like you want something which is not directly possible: operator[][].

You can emulate the behavior of this by using an intermediate class:
Since a Matrix class is typically indexed as [rows][columns], you can
have the first operator method return the corresponding Row object.
The row class can than overload the operator[] and return the corresponding
element.

Row& Matrix::operator[](int r);  
double& Row::operator[](int c);

Now when you create your matrix object, you can index it as expected:

Matrix matrix(3,3);  
matrix[0][0] = 1;

The last line is then equivalent to calling:

matrix.operator[](0).operator[](0) = 1;

To check for out-of-bounds indices, store the matrix sizes:

Proxy operator[](int index) {
    assert(index < num_rows);
    return Proxy(_arrayofarrays[index]);
}

double &operator[](int index) const {
    assert(index < num_cols);
    return _array[index];
}

As Aldo suggeested, Proxy can be passed the array length value in it's constructor:

 Proxy(double* _array, int _length) : _array(_array), num_cols(_length){
 }

As a general rule of thumb, if you're passing a raw array to a function, you will almost always want to pass the length of that array as well.

Upvotes: 2

aldo
aldo

Reputation: 2987

Your Proxy::operator[] overload is returning a double&. This double& is the object that will eventually be assigned to by client code, and you can't intercept that (at least not easily). Probably what you need to do is to check the index parameter in your operator[] overloads, and throw your own exception there rather than passing that index along to your internal arrays.

Upvotes: 1

Related Questions