Перегрузка операторов в C++ и разыменование

Я сейчас практикую перегрузку операторов в C++, и у меня возникла проблема.Я создал класс String, он имеет только поля, одно из которых представляет собой массив символов, а другое - длину. У меня есть строка «У Алисы есть кошка», и когда я звоню

cout<<moj[2];

, я хотел бы получить «i», но теперь я получаю адрес moj + 16u + 2 sizeof (String) Когда я вызываю

 cout<<(*moj)[2];

, он работает так, как должен, но я хотел бы разыменовать его в перегруженном определении оператора. Я пробовал много вещей, но я не могу найти решение. Пожалуйста, поправьте меня.

char & operator[](int el) {return napis[el];}
const char & operator[](int el) const {return napis[el];}

И весь код, важные вещи находятся внизу страницы. Он компилируется и работает.

    #include <iostream>
   #include <cstdio>
   #include <stdio.h>
   #include <cstring>
  using namespace std;

 class String{
public:

//THIS IS  UNIMPORTANT------------------------------------------------------------------------------
char* napis;
int dlugosc;
   String(char* napis){
   this->napis = new char[20];
   //this->napis = napis;
   memcpy(this->napis,napis,12);
   this->dlugosc = this->length();
}

   String(const String& obiekt){
   int wrt = obiekt.dlugosc*sizeof(char);
   //cout<<"before memcpy"<<endl;
   this->napis = new char[wrt];
   memcpy(this->napis,obiekt.napis,wrt);

   //cout<<"after memcpy"<<endl;
   this->dlugosc = wrt/sizeof(char);
  }

   ~String(){
   delete[] this->napis;
   }

   int length(){
   int i = 0;
   while(napis[i] != '\0'){
       i++;
   }
   return i;
  }
        void show(){
      cout<<napis<<" dlugosc = "<<dlugosc<<endl;
 }


//THIS IS IMPORTANT
    char & operator[](int el) {return napis[el];}
    const char & operator[](int el) const {return napis[el];}
};


   int main()
   {

   String* moj = new String("Alice has a cat");
  cout<<(*moj)[2]; // IT WORKS BUI
 //  cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE


   return 0;
   }
5
задан Yoda 2 June 2012 в 22:03
поделиться