C++-代入演算子の再ロード

2351 ワード

  • 賦値演算子の両方のタイプが一致しなくてもよい
  • int型変数をComplexオブジェクト
  • に割り当てる
  • char*タイプの文字列を文字列オブジェクト
  • に割り当てる
  • は、代入演算子'='
  • を再ロードする必要があります.
  • 賦課演算子"="は、メンバー関数
  • にのみ再ロードできます.
  • 長さ可変文字列クラスStringを記述
  • char*タイプのメンバー変数->動的に割り当てられたストレージ領域を指す
  • "0"の末尾を格納文字列
  • class String{
          private:
              char *str;
        public:
              String():str(NULL){}//    
              const char * c_str() {return str; }//   ,                      ,       const   
              char * operator = (const char * s);
              ~String();
    }
    //  '='->obj = "hello"    
    char *String :: operator = (const char * s){
        if(str)delete[]str;//            ,   
        if(s){
            str = new char[strlen(s)+1];//        '\0',   +1
            strcpy(str,s);
        }
        else
            str = NULL;
        return str;
    }
    String::~String(){
        if(str) delete []str;
    };
    int main(){
          String s;
          s = "Good Luck,"; //-->s.operator = ("")
          cout<
  • 賦課演算子のリロードの意味-浅いレプリケーションと深いレプリケーション
  • MyString S1,S2;
    S1 = "this";
    S2 = "that";
    S1 = S2;
    
    -    :   S1    “this”           "that"        ,     S2     "that"             。         :
        *    “this”         
        *   S1   S2       ,   “that”         ,      。
    -    :  “that”       “this”      ,                。
    
  • class MyStringにメンバー関数を追加する:
  • //     
    String & operator = (const String & s){
        if(str == s.str)return * this;//                   ,          。  :s = s
        if(str) delete [] str;
        str = new char[strlen(s.str)+1];
        strcpy(str,s.str);
        return * this;
    }
    
  • operarpr=戻り値タイプについての議論
  • void:
  • a=b=cを用いると2番目の式のサブパラメータが0となる.

  • Stringはいいですか?なぜString&演算子がリロードされたのか、演算子の本来の特性をできるだけ保持し、考慮:
  • (a=b)=c;//    a   
       :  
      (a.operator =(b)).operator=(c);
    
  • Stringクラスにレプリケーションコンストラクタを記述する場合
  • .
  • は"="と同様の問題に直面し、
  • を同様の方法で処理する.
    //               ,                 
    String::String(String & s)
    {
        if(s.str){
              str = new char[strlen(s.str)+1];
              strcpy(str,s.str);
         }else{
              str = NULL;
          }
    }