By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,435 Members | 1,372 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,435 IT Pros & Developers. It's quick & easy.

HOW overloaded operator eg [],(),->

sanjay123456
100+
P: 125
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
Dec 25 '06 #1
Share this Question
Share on Google+
6 Replies


P: 30
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
i would like to know the answer to this question two
does anyone knows a solution?
Dec 26 '06 #2

100+
P: 145
i would like to know the answer to this question two
does anyone knows a solution?
You need to add something like

Expand|Select|Wrap|Line Numbers
  1. double* operator()( int i, int j );
  2.  
to your class. (Replace double* with whatever you deem appropriate for the class.) For instance, I use the operator() as follows in my EasyBMP code:

Expand|Select|Wrap|Line Numbers
  1. BMP
  2. {
  3.  private:
  4.   RGBApixel** Pixels;
  5.   // ... more stuff
  6.  public:
  7.   RGBApixel* operator()(int i, int j);
  8.   // ... more stuff
  9. };
  10.  
  11. RGBApixel* BMP::operator()( int i, int j)
  12. { return &( Pixels[i][j] ); }
  13.  
In use, it works like this:
Expand|Select|Wrap|Line Numbers
  1. BMP SomeImage;
  2. SomeImage.ReadFromFile( "blah.bmp" );
  3.  
  4. cout << "pixel (3,2): (" 
  5.      << (int) SomeImage(3,2)->Red   << ","
  6.      << (int) SomeImage(3,2)->Green << ","
  7.      << (int) SomeImage(3,2)->Blue  << ")" << endl;
  8.  
I hope that helps point you in the right direction. -- Paul
Dec 26 '06 #3

Expert 100+
P: 1,510
Dear firiends ,
tell me that HOW overloaded operator eg [],(),->
how can i overloaded those operator

sanjay
below is some sample code from a 2D matrix class I implemented years ago
Expand|Select|Wrap|Line Numbers
  1. // Matrix class
  2. // uses an array of pointers p_rows which contains the start address of each row 
  3. //  in stored the array p_matrix, i.e. the address of element [row][column] is
  4. //      p_rows[row] + column      
  5. class Matrix                                               // define type Matrix
  6.       { // private members
  7.            string name;                                           // name of array
  8.            float *p_matrix;          // pointer to array of float to hold matrix
  9.            float **p_rows;                         // pointer to rows in p_array
  10.            int columns, rows;                   // size of matrix(rows, columns)
  11.         // member function, return reference to array element (row, column)
  12.            float & index(const int row, const int column) const
  13.               { return *(p_rows[row] + column); }
  14.  
  15. ...
  16.  
operator[] would be (no array bounds checking)
Expand|Select|Wrap|Line Numbers
  1.        // return pointer to array element indexed by ex_row, indexed from 1
  2.            float * operator[](const int ex_row) const
  3.                { return (p_rows[ex_row - 1] - 1); }
  4.  
operator() would be (throws exception on array index out of bounds)
Expand|Select|Wrap|Line Numbers
  1. // return reference to array element (ex_row, ex_col), indexed from 1         //
  2. //  throw exception if array index out of bo                                  //
  3. float & Matrix::operator()(int ex_row, int ex_col) const 
  4.     if ((ex_row < 1) || (ex_col < 1) || (ex_row > rows) || (ex_col > columns)) 
  5.        {
  6.         // error! create message for throwing exception
  7.         stringstream ss;
  8.         ss <<  " Matrix::operator() array " << name << 
  9.           "(" << ex_row  << "," << ex_col << ") out of bounds";
  10.         string s=ss.str();
  11.         throw out_of_range(s);       // out of bounds exception
  12.        }
  13.     return this->index(ex_row - 1, ex_col - 1);   // return reference to element 
  14. }
  15.  
full code is available from
http://www.geocities.com/horacespider/programming/C/matrix.txt
Dec 27 '06 #4

100+
P: 145
...
Exactly. :) Do note that if you make the function const, then your operator() will only be able to fetch the matrix value, but won't be able to change the matrix value. That's why I tend to not make it const when I write matrix libraries, so that you can use it in a way you'd use it on paper, e.g.,

*Matrix1(3,2) = *Matrix2(4,0);

A very simple 2D array class is included as part of the EasyBMP Extensions. (It doesn't actually rely upon EasyBMP.) It's fully open source, so you're free to look it over and use/abuse it as you see fit. :)

In the way the implementation is done, you can do things like this:
Expand|Select|Wrap|Line Numbers
  1. SimpleArray InputData;
  2. InputData.ReadFromFile( "PHI.dat" );
  3. SimpleArray OutputData( InputData.Rows, InputData.Cols );
  4. int i,j;
  5. for( i=0 ; i < InputData.Rows ; i++)
  6. {
  7.  for( j=0 ; j < InputData.Cols ; j++)
  8.  {
  9.   *OutputData(i,j) = pow( *InputData(i,j) , 2.0 ); 
  10.  }
  11. }
  12.  
Horace raised a good point about accessing data elements that are out of bounds. As he pointed out, you can check the bounds when you return the memory address. Another thing you can do, rather than throw and exception, is crop the index and give the user a warning. I do this with the operator() on my EasyBMP library. Here's an adaptation:
Expand|Select|Wrap|Line Numbers
  1. class Matrix
  2. {
  3.  private:
  4.   int Rows;
  5.   int Cols;
  6.   double** Data;
  7.   // ... etc
  8.  
  9.  public:
  10.   double* operator()( int i, int j );
  11.   // ... etc
  12. };
  13.  
  14. double* Matrix::operator()( int i, int j )
  15. {
  16.  if( i < 0 || i >= Rows )
  17.  { 
  18.   cout << "Matrix Warning: index " << i << " was out of bounds!" << endl
  19.        << "Cropping to range [0," << Rows-1 << "]" << endl;
  20.   if( i < 0 ){ i = 0; }
  21.   if( i >= Rows ){ i = Rows-1; }
  22.  }
  23.  if( j < 0 || j >= Cols )
  24.  { 
  25.   cout << "Matrix Warning: index " << j << " was out of bounds!" << endl
  26.        << "Cropping to range [0," << Cols-1 << "]" << endl;
  27.   if( j < 0 ){ j = 0; }
  28.   if( j >= Cols ){ j = Cols-1; }
  29.  }
  30.  return &( Data[i][j] );
  31. }
  32.  
Do note, however, that checks like these will slow the program down. If you know for certain that the programmer will only access correct matrix entries, you can cut those checks to speed up execution. -- Paul
Dec 27 '06 #5

Expert 100+
P: 1,510
macklin01 makes a good point about operator[] - in practice many functions need two versions one for 'normal' obects and one for constant objects,e.g in <vector>
http://www.cppreference.com/cppvector/vector_operators.html
shows
Expand|Select|Wrap|Line Numbers
  1. TYPE& operator[]( size_type index );
  2. const TYPE& operator[]( size_type index ) const;
  3.  
also the point about error checking is critical - the more you do the longer the execution time. e.g. in <vector> to access an element you can use at() or [] but
http://www.cppreference.com/cppvector/at.html
states "The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector."
Dec 27 '06 #6

Expert 100+
P: 1,510
macklin01 makes a good point about operator[] - in practice many functions need two versions one for 'normal' obects and one for constant objects,e.g in <vector>
http://www.cppreference.com/cppvector/vector_operators.html
shows
Expand|Select|Wrap|Line Numbers
  1. TYPE& operator[]( size_type index );
  2. const TYPE& operator[]( size_type index ) const;
  3.  
also the point about error checking is critical - the more you do the longer the execution time. e.g. in <vector> to access an element you can use at() or [] but
http://www.cppreference.com/cppvector/at.html
states "The at() function is safer than the [] operator, because it won't let you reference items outside the bounds of the vector.", i.e. [] does no array bounds checking.
Dec 27 '06 #7

Post your reply

Sign in to post your reply or Sign up for a free account.