Overload operator in C ++ and dereferencing

I'm dealing with operator overloading in C ++ right now, and I have a problem. I created a String class, it has only one field: char array other is length. I have the line "Alice has a cat" and when I call

cout<<moj[2];

I would like to get "i", but now I get moj + 16u address moj + 2 sizeof (String) When I call

 cout<<(*moj)[2];

it works as we would like, but I would like to dereference it in the overloaded operator definition. I have tried many things, but I can not find a solution. Please correct me.

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

And all the code, important things are on the page. It compiles and works.

    #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
source share
2 answers
String* moj = new String("Alice has a cat");
cout<<(*moj)[2]; // IT WORKS BUI
//  cout<<moj[2]; //I WOULD LIKE TO USE THIS ONE

, . , ( , ); String* 2, .

, , , :

String moj("Alice has a cat");
// cout<<(*moj)[2]; <-- now this doesn't work
cout<<moj[2]; // <-- but this does
+8

String * String, - String, *moj. :

String moj = String("Alice has a cat"); // note lack of * and new
cout << moj[2];

, , new, :

String *x = new String("foo");

// code

delete x;
+3

All Articles