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:
char* napis;
int dlugosc;
String(char* napis){
this->napis = new char[20];
memcpy(this->napis,napis,12);
this->dlugosc = this->length();
}
String(const String& obiekt){
int wrt = obiekt.dlugosc*sizeof(char);
this->napis = new char[wrt];
memcpy(this->napis,obiekt.napis,wrt);
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;
}
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];
return 0;
}
source
share