string類中“+”操作符重載(三種形式)

class MyString
{
public:
MyString(char *s)                      //有參構造函數;
{
str=new char[strlen(s)+1];
strcpy(str,s);
}

~MyString()                              //析構函數;
{
delete []str;
str==nullptr;
}

MyString (const MyString &strOther)        //複製構造函數;
{
str=new char[strlen(strOther.str)+1];
strcpy(str,strOther.str);
}

MyString & operator=(MyString &strOther)     //賦值函數(“=”重載)
{
if(this==&strOther)
return *this;
if(str!=nullptr)
delete [] str;
str=new char[strlen(strOther.str)+1];
strcpy(str,strOther.str);
return *this;
}

MyString & operator+(MyString &strOther)       //"+"重載(改變被加對象)             
{
char *temp=str;                             
str=new char[strlen(temp)+strlen(strOther.str)+1];
strcpy(str,temp);  //複製第一個字符串;                      
delete[] temp;
strcat(str,strOther.str); //連接第二個字符串;
return *this;             //返回改變後的對象;
}

MyString & operator+(MyString &strOther)            //"+"重載(不改變被加對象)
{
MyString *pString=new MyString("");            //堆內存中構造對象;
pString->str=new char[strlen(str)+strlen(strOther.str)+1];
strcpy(pString->str,str); //複製第一個字符串;
strcat(pString->str,strOther.str);//連接第二個字符串;
return *pString;             //返回堆中對象;

}

private:
char *str;
};



//MyString類的友元,要求str成員是public訪問權限; //"+"重載(不改變被加對象)

MyString & operator(MyString &left,MyString &right)
{
MyString *pString=new MyString("");
pString->str=new char[strlen(left.str)+strlen(right.str)+1];
strcpy(pString->str,left.str);
strcat(pString->str,right.str);
return *pString;
}




//三個"+"操作符重載函數均是調用strcpy複製第一個字符串,調用strcat連接第二個字符串;

1、第一個返回*this對象,它改變了被加對象;屬於類的成員函數;
2、第二個返回堆中構造的對象,它沒有改變被加對象;屬於類的成員函數;

3、第三個都返回堆中構造的對象,它沒有改變被加對象;屬於友元函數(前提是
    需要str成員的訪問權限改爲public,因爲友元函數不能訪問類的私有成員,且友元函數沒有this指針) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章