2016-04-12 25 views
-3

こんにちは私はC++で文字列クラスを作成していますが、演算子+(const char *)に演算子+(const string & string1)を再利用し、演算子+と演算子= + =(const文字列& string1)および演算子+ =(const char *)。私のコードは以下の通りです。みんなありがとう:)C++でコード(関数)を再利用する方法

String& String::operator=(const String& string1) { 
    using std::nothrow; 
    using std::endl; 
    using std:: cout; 

    destroy(); 
    size = string1.getSize(); 
     // if (*this != string1){ 
    if (getSize() != 0) 
    { 
     data = new (nothrow) char[getSize()]; 
     if (data == NULL) 
     cout<<" ERROR message not enough memory allocated)"<<endl; 
     else 
     { 
      for (unsigned int i = 0; i < getSize(); i++) 
      data[i] = string1.data[i]; 
     } 
    } 
    return *this; 
} 

String& String::operator=(const char * cstring) { 

    String temp(cstring); 
    temp = *this; 
    return temp; 
} 

String& String::operator +(const String& string1){ 
    using std::nothrow; 
    using std::endl; 
    using std:: cout; 


    String temp; 
    //destroy(); 
    //char * temp = new char[size]; 

    temp.size = getSize() + string1.getSize(); 
    //char * temp = new char[size]; 

     if (getSize() != 0) 
     { 

      temp.data = new (nothrow) char[getSize()]; 

     if (temp.data == NULL) 
     { 
      cout<< "ERROR"<<endl; 
     } 
     else 
     { 

     for (unsigned int i = 0; i < temp.getSize(); i++) 
      temp.data[i]= data[i]; 

     int j = 0; 
     for (unsigned int i = temp.getSize(); i < string1.getSize(); i++) 
     { 
      temp.data[i] = string1.data[j]; 
      j++; 
     } 
    } 
} 
    return temp; 
} 

String& String::operator+(const char *string1){ 

    //not correct. i have to resue operator + 
    String temp (string1); 
    (*this)+(); 
return (temp) 
} 
String & String::operator+=(const char *string1){ 
// I have to reuse operator + and operator = 

//String temp (string1); 
//(*this)+(temp); 
return (temp) 

}あなたの文字列型である限り

+1

だから問題は何ですか? – kirkpatt

+1

一般に '+'は '+ ='を使います。 – Jarod42

+0

あなたの代入演算子は、自己代入でブレークします。 –

答えて

0

は、あなたが自由のためにこれらを得るでしょうconst char*を取るコンストラクタを持っています。コンパイラは、Cスタイルの文字列を、その文字列型が必要な場合はいつでも、そのコンストラクタを使用して文字列型に変換します。例えば、

String346 str("abcd"); 
String346 res = str + "efgh"; 

これは、メンバ関数operator+(const String346&)を使用して、res"abcdefgh"を格納します。

しかし、それはいくつかの理由からoperator+のための良いインタフェースではありません。代わりに、いくつかのコメントが示すように、operator+=をメンバ関数にし、operator+(const String346&, const String346&)をフリー関数として定義し、operator+=で実装します。

これを行うと、変換は引き続き有効です。

+0

ご協力ありがとうございます。私は高く評価します –

+0

また、演算子+と演算子+ =メンバ関数を作ると仮定します –

+0

@ isaac_34 - 大丈夫、私の答えの最後の2つの段落を無視します。

関連する問題