Re: Overloading Operator[] through 'this' pointer?
 
Immortal Nephi <Immortal_Nephi@hotmail.com> writes:
    
Can overloading operator[] be connected to any member functions
through ??this?? pointer?  I do not want to insert assignment between
array object and integer value.  I prefer to place integer value in
the member function??s parameter.
For example:
class Array
{
public:
    Array( int size ) : pData( new unsigned char[ size ] )
    {}
    ~Array()
    {
        delete [] pData;
    }
    int &operator[]( int index )
    {
        return pData[ index ];
    }
    Array &Set_LowNibble( unsigned char val, int index )
    {
        pData[ index ] &= 0xF0;
        pData[ index ] |= (val & 0x0F );
        return *this;
    }
    Array &Set_HighNibble( unsigned char val, int index )
    {
        pData[ index ] &= 0x0F;
        unsigned char temp = val;
        temp &= 0x0F;
        temp <<= 4;
        pData[ index ] |= temp;
        return *this;
    }
private:
    unsigned char *pData;
};
int main()
{
    Array array( 4 );
    array[ 0 ] = 0x1E; // Always valid code
    // Not valid code but you find another way
    array[ 1 ].Set_LowNibble( 0x0D, 1 ).Set_HighNibble( 0x02, 1 );
    return 0;
}
The following is just an idea to think about.  I have not given very
much consideration to the details and I am not completely sure why you
are wanting it to work in this way.
   class Byte
   {
   public:
      Byte(unsigned char& c) : c_(c) { }
      Byte& operator=(unsigned char val)
      {
         c_ = val;
         return *this;
      }
      Byte& Set_LowNibble(unsigned char val)
      {
         c_ &= 0xF0;
         c_ |= (val & 0x0F);
         return *this;
      }
      Byte& Set_HighNibble(unsigned char val)
      {
         c_ &= 0x0F;
         unsigned char temp = val;
         temp &= 0x0F;
         temp <<= 4;
         c_ |= temp;
         return *this;
      }
      operator unsigned char&() { return c_; }
   private:
      unsigned char& c_;
   };
   class Array
   {
   public:
      Array(int size)
         : pData(new unsigned char[size])
      { }
      ~Array()
      {
         delete [] pData;
      }
      Byte operator[](int index)
      {
         return pData[index];
      }
   private:
      unsigned char *pData;
   };
   int main()
   {
      Array array(4);
      array[0] = 0x3C;
      array[1].Set_LowNibble(0x0D).Set_HighNibble(0x02);
      std::cout << array[0] << '\n';
      std::cout << array[1] << '\n';
      unsigned char& c_ref = array[1];
      c_ref = array[0];
      std::cout << array[0] << '\n';
      std::cout << array[1] << '\n';
      return 0;
   }
   /**
    * Output:
    *    <
    *    -
    *    <
    *    <
    */
Regards
Paul Bibbings