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指针)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.