2017-10-11 16 views
-5

3つの[0] = 'p'を作りたいと思います。以下のコードで作業してください。私はそれのために演算子をオーバーロードさせる必要があると思うが、私はどのように行うのか分からない。私が得たいのは、「宝くじ当選者」の最初の指標を変更することです。上'。 ( "陶器の勝者を得るために!")。C++の演算子[]の演算子オーバーロードを書く方法

#include<iostream> 
#include<cstring> 
using namespace std; 

class str 
{ 
    char* a; 
public: 
    str(char *aa=""){ 
    this->a = new char[strlen(aa)+1]; 
    strcpy(a,aa); 
} 

~str(){ 
    delete a; 
} 

friend ostream& operator<<(ostream &out, str &aa); 
friend istream& operator>>(istream &in, str &aa); 

}; 
ostream& operator<<(ostream &out, str &aa){ 
    out<<aa.a; 
    return out; 
} 

istream& operator>>(istream &in, str &aa){ 
    in>>aa.a; 
    return in; 
} 

void main(){ 
    str three("Lottery winner!"); 
    three[0]='p'; 
    cout<<three<<endl; 
} 
+3

[オペレータのオーバーロードの基本ルールとイディオムは何ですか?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading ) – user0042

答えて

1

これはoperator[]の一般的な署名である:あなたの文脈では

T& operator[](any_type); 

それは次のようになります。

struct str { 

    ... 

    char& operator[](std::size_t pos) { 
     return a[pos]; 
    } 

}; 
0
class str 
{ 
    // ... 
public: 
    // ... 
    char& operator[] (int x) 
    { 
     // add array out-of-bounds check here if you like to ... 
     return a[x]; 
    } 
} 
+1

境界チェックは通常、 'at()'メソッドでのみ行われます。 – OutOfBound

0
operator char*() 
{ 
    return a; 
} 

を仕事ができます
関連する問題