現在、C++でオーバーロード演算子を練習していますが、問題があります。 私はStringクラスを作成しました。これは、フィールドの1つがchar配列であり、その他はlengthです。 私は文字列「アリスが猫を持っている」持っていると私は私が「i」を取得したいと思いますが、今、私は+ 2のsizeof(文字列) 法務省の16U +法務省アドレスを取得していますC++での演算子のオーバーロードと逆参照
cout<<moj[2];
を呼び出します私は
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;
}
あなたは '法務省を削除する必要があります;'返す前に。 – Matt
最小のコードがあるように削除しました。 – Yoda