Kai-Uwe Bux
11/4/2008 12:46:00 AM
jr.freester@gmail.com wrote:
> On Nov 3, 6:58 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
>> jr.frees...@gmail.com wrote:
>> > I've written a Matrix container class and overloaded the function call
>> > operator to return values at a specified index.
>> > Below is the member function
>>
>> > double operator()(int a , int b)
>>
>> Probably, it is not the best idea to allow signed arguments.
>>
>> > {
>> > if((a < 1) || (b < 1) || ((a + 1) > this->row) || ((b + 1) > this-
>> >>col))
>>
>> Probably, it would be better to go with the C convention to start
>> indexing at 0. This will get rid of many "-1" in the code, which are
>> prone to error.
>>
>> > {
>> > cerr << "Invalid index for Matrix" <<endl;
>>
>> This should be an assert().
>>
>> In an at()-method, it you would throw something.
>>
>> > }
>>
>> > return this->data[(a-1)*this->col + (b-1)];
>> > }
>>
>> > It is invoked
>> > int row, col;
>> > double d;
>> > Matrix M;
>> > d = M(row,col);
>>
>> > My question is thus, can I accomplish the reverse task of assigning a
>> > double d to a Matrix M at power row,col ie.
>> > M(row,col) = d;
>>
>> Yes, return a reference
>>
>> double & operator()( size_type a, size_type b );
>>
>> Best
>>
>> Kai-Uwe Bux
>
> Kai-Uwe, thank you for your quick response, but I am having trouble
> understanding the last statement.
>> Yes, return a reference
>>
>> double & operator()( size_type a, size_type b );
>
> what would the body of this function look like?
e.g.:
double & operator()( size_type a, size_type b ) {
assert( a < this->row );
assert( b < this->col );
return( this->data[ a * this->col + b ] );
}
> I don't understand
> how adding the reference operator changes the order of assignment of
> M(a,b) -> d TO d -> M(a,b).
It doesn't. It affects how expressions in the return statement are
interpreted. In this case,
this->data[ a * this->col + b ]
is interpreted as a reference. Note that by and in itself,
this->data[ a * this->col + b ]
is an lvalue. In particular,
this->data[ a * this->col + b ] = some_thing;
would be well-formed. That magic can be wrapped up in a reference and be
returned.
Best
Kai-Uwe Bux