2012-06-02 8 views
5

現在、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; 
    } 
+0

あなたは '法務省を削除する必要があります;'返す前に。 – Matt

+0

最小のコードがあるように削除しました。 – Yoda

答えて

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

、後者の場合に添字演算子はポインタに適用されます。少なくとも1つの引数がユーザ定義型(またはポインタを指すのではなく参照)である場合にのみ、演算子をオーバーロードすることができます。この特定のケースでは、引数は両方とも基本型のString*2です。あなたが行うことは何

はあなたがそれを必要とする理由私は見ていない、完全にポインタをドロップです:あなたはString自体あなたと一緒に何かをしたい場合は

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

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; 
関連する問題