Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator
sanjay
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator
sanjay
double* operator()( int i, int j );
BMP
{
private:
RGBApixel** Pixels;
// ... more stuff
public:
RGBApixel* operator()(int i, int j);
// ... more stuff
};
RGBApixel* BMP::operator()( int i, int j)
{ return &( Pixels[i][j] ); }
BMP SomeImage;
SomeImage.ReadFromFile( "blah.bmp" );
cout << "pixel (3,2): ("
<< (int) SomeImage(3,2)->Red << ","
<< (int) SomeImage(3,2)->Green << ","
<< (int) SomeImage(3,2)->Blue << ")" << endl;
// Matrix class
// uses an array of pointers p_rows which contains the start address of each row
// in stored the array p_matrix, i.e. the address of element [row][column] is
// p_rows[row] + column
class Matrix // define type Matrix
{ // private members
string name; // name of array
float *p_matrix; // pointer to array of float to hold matrix
float **p_rows; // pointer to rows in p_array
int columns, rows; // size of matrix(rows, columns)
// member function, return reference to array element (row, column)
float & index(const int row, const int column) const
{ return *(p_rows[row] + column); }
...
// return pointer to array element indexed by ex_row, indexed from 1
float * operator[](const int ex_row) const
{ return (p_rows[ex_row - 1] - 1); }
// return reference to array element (ex_row, ex_col), indexed from 1 //
// throw exception if array index out of bo //
float & Matrix::operator()(int ex_row, int ex_col) const
{
if ((ex_row < 1) || (ex_col < 1) || (ex_row > rows) || (ex_col > columns))
{
// error! create message for throwing exception
stringstream ss;
ss << " Matrix::operator() array " << name <<
"(" << ex_row << "," << ex_col << ") out of bounds";
string s=ss.str();
throw out_of_range(s); // out of bounds exception
}
return this->index(ex_row - 1, ex_col - 1); // return reference to element
}
SimpleArray InputData;
InputData.ReadFromFile( "PHI.dat" );
SimpleArray OutputData( InputData.Rows, InputData.Cols );
int i,j;
for( i=0 ; i < InputData.Rows ; i++)
{
for( j=0 ; j < InputData.Cols ; j++)
{
*OutputData(i,j) = pow( *InputData(i,j) , 2.0 );
}
}
class Matrix
{
private:
int Rows;
int Cols;
double** Data;
// ... etc
public:
double* operator()( int i, int j );
// ... etc
};
double* Matrix::operator()( int i, int j )
{
if( i < 0 || i >= Rows )
{
cout << "Matrix Warning: index " << i << " was out of bounds!" << endl
<< "Cropping to range [0," << Rows-1 << "]" << endl;
if( i < 0 ){ i = 0; }
if( i >= Rows ){ i = Rows-1; }
}
if( j < 0 || j >= Cols )
{
cout << "Matrix Warning: index " << j << " was out of bounds!" << endl
<< "Cropping to range [0," << Cols-1 << "]" << endl;
if( j < 0 ){ j = 0; }
if( j >= Cols ){ j = Cols-1; }
}
return &( Data[i][j] );
}
TYPE& operator[]( size_type index ); const TYPE& operator[]( size_type index ) const;
TYPE& operator[]( size_type index ); const TYPE& operator[]( size_type index ) const;
Comment