0
class mystring { 
private:
 string s;
public:
 mystring(string ss) { 
  cout << "mystring : mystring() : " + s <<endl; 
  s = ss;
 }
 /*! mystring& operator=(const string ss) { 
  cout << "mystring : mystring& operator=(string) : " + s <<endl;
  s = ss; 
  //! return this; 
  return (mystring&)this; // why COMPILE ERROR
 } */
 mystring operator=(const string ss) {
  cout << "mystring : mystring operator=(string) : " + s <<endl;
  s = ss;
  return *this;
 } 
 mystring operator=(const char ss[]) {
  cout << "mystring : mystring operator=(char[]) : " << ss <<endl;
  s = ss;
  return *this;
 }
};

mystring str1 =  "abc"; // why COMPILE ERROR
mystring *str2 = new mystring("bcd");

だから質問は

  1. 正しいmystring&opeartor =オーバーロードを作成する方法、つまり、ポインターではなく参照を返すにはどうすればよいですか(C ++で参照とポインターの間を転送できますか?)

  2. 正しいmystringoperator=overloadを作成する方法?ソースコードは正常に機能すると思いましたが、operator =をオーバーロードしなかったかのように、mystringにconstchar[]を割り当てることができませんでした。

ありがとう。

4

4 に答える 4

5

必要なのは、const char*:を取る「変換」コンストラクターです。

mystring( char const* ss) {
  cout << "mystring : mystring(char*) ctor : " << ss <<endl;
  s = ss;
}

問題が発生している行:

mystring str1 =  "abc"; // why COMPILE ERROR

実際には割り当てではありません-初期化子です。

于 2009-12-24T05:05:25.537 に答える
3
mystring& operator=(const string &ss) 
{
    cout << "mystring : mystring operator=(string) : " + s <<endl;
    s = ss;

    return *this; // return the reference to LHS object.
} 
于 2009-12-24T04:56:40.327 に答える
0

他の人が指摘したように、タイプ"string"const char *あり、代入演算子をオーバーロードする必要があります。

mystring& operator=(const char * s);

ポインターから参照を取得する*thisだけで十分です。何もキャストする必要はありません。

于 2009-12-24T05:01:30.780 に答える
0
 mystring& operator=(const string& ss) {
  cout << "mystring : mystring operator=(string) : " << s << endl;
  s = ss;

  return *this;
 } 
 mystring& operator=(const char* const pStr) {
  cout << "mystring : mystring operator=(zzzz) : " << pStr << endl;
  s = pStr;

  return *this;
 }
  • 文字列に '&' を追加したので、コピーではなく 'this' への参照が返されます (不必要に入力文字列のコピーを作成しないため、入力パラメーターに対してもこれを行うことをお勧めします)。 、
  • 2行目で「+」を「<<」に交換しました
  • そして、配列を const char const* ポインターに変更しました
于 2009-12-24T09:02:56.430 に答える