Elementfunktion + Überladen



  • class Array
    {
       int data[4];
     public:
      int &operator[](unsigned int index) 
      {                  
        return data[index];              
       }
    
       int operator[](unsigned int index) const  
       {  
         return ((Array *)this)->operator[](index); 
       }
    };
    
    int main() 
    { Array arr;
        for(int i = 0; i < 4; i++)
       {
         arr[i]=11*(i+1);
        }
    }
    

    Wann wird die Elementfunktion &operator[]() und wann operator[] aufgerufen??
    Die machen doch beide das gleiche, oder sehe ich das falsch??


  • Mod

    die erste überladung wird aufgerufen, wenn sein objektparamter (also das array) nicht const qualifiziert ist. die zweite überladung dann, wenn das array const-qualifiziert ist. also:

    Array arr;
    arr[0]; // int &operator[](unsigned int index)
    const Array& c_arr = arr;
    c_arr[0]; // int operator[](unsigned int index) const
    const Array arr2;
    arr2[0]; // int operator[](unsigned int index) const
    

Anmelden zum Antworten