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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sanjay123456
    New Member
    • Sep 2006
    • 125

    #1

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

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

    sanjay
  • asdfghjkl2007
    New Member
    • Oct 2006
    • 30

    #2
    Originally posted by sanjay123456
    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?

    Comment

    • macklin01
      New Member
      • Aug 2005
      • 145

      #3
      Originally posted by asdfghjkl2007
      i would like to know the answer to this question two
      does anyone knows a solution?
      You need to add something like

      Code:
      double* operator()( int i, int j );
      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:

      Code:
      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] ); }
      In use, it works like this:
      Code:
      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;
      I hope that helps point you in the right direction. -- Paul

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        Originally posted by sanjay123456
        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
        Code:
        // 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); }
        
        ...
        operator[] would be (no array bounds checking)
        Code:
               // 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); }
        operator() would be (throws exception on array index out of bounds)
        Code:
        // 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 
        }
        full code is available from
        http://www.geocities.c om/horacespider/programming/C/matrix.txt

        Comment

        • macklin01
          New Member
          • Aug 2005
          • 145

          #5
          Originally posted by horace1
          ...
          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:
          Code:
          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 ); 
           }
          }
          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:
          Code:
          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] );
          }
          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

          Comment

          • horace1
            Recognized Expert Top Contributor
            • Nov 2006
            • 1510

            #6
            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.cppreferenc e.com/cppvector/vector_operator s.html
            shows
            Code:
            TYPE& operator[]( size_type index );
            const TYPE& operator[]( size_type index ) const;
            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.cppreferenc e.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."

            Comment

            • horace1
              Recognized Expert Top Contributor
              • Nov 2006
              • 1510

              #7
              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.cppreferenc e.com/cppvector/vector_operator s.html
              shows
              Code:
              TYPE& operator[]( size_type index );
              const TYPE& operator[]( size_type index ) const;
              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.cppreferenc e.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.

              Comment

              Working...