質問

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 = overloadを作成する方法は、ポインターではなく参照を返すにはどうすればよいですか?

  2. 正しいMyStringオペレーター=オーバーロードを作成する方法?ソースコードは正常に動作すると思いましたが、オペレーター=をオーバーロードしないかのように、const char []をmystringに割り当てることができなかったことがわかります。

ありがとう。

役に立ちましたか?

解決

必要なのは、 const char*:

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

あなたが問題を抱えているライン:

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

本当に割り当てではありません - それはイニシャルです。

他のヒント

mystring& operator=(const string &ss) 
{
    cout << "mystring : mystring operator=(string) : " + s <<endl;
    s = ss;

    return *this; // return the reference to LHS object.
} 

他の人が指摘したように、 "string" もっている const char * タイプすると、割り当てオペレーターをオーバーロードする必要があります。

mystring& operator=(const char * s);

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

 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;
 }
  • 文字列に「&」を追加して、「これ」のコピーではなく「これ」への参照を返します(入力パラメーターについても、入力文字列のコピーを作成していないため、それを行うのは良い習慣です) 、
  • 2行目に「+」を<< 'に交換しました
  • そして、私はあなたの配列をaに変更しましたconst char const*ポインター
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top