浅析C++中的重载运算符(重点是重载+=)

C++中的重载运算符很多人再熟悉不过了,你可能会轻松的写出重载+,-,*,/。但是当你第一次写重载+=时,也许会有些迷茫。

先来点家常的,写一个赋值运算符:

Contact& operator=( const Contact& rhs ) {
    if(this == &rhs)
        return *this
   char* tempName = new char[strlen( rhs.name ) + 1];
   delete[] name;
   name = tempName;
   strcpy( name, rhs.name );
   age = rhs.age;
   return *this;
}

第一个问题,为何返回对象的引用:
答曰:可以实现对象的连等。

再来段家常的:

Time operator+(const Time & t)const
{
    Time sum;
    sum.minutes = minutes + t.minutes ;
    sum.hours = hours + t.hours + sum.minutes / 60;
    sum.minutes %= 60;
    return sum;
}
Time operator-(const Time & t)const
{
    Time diff;
    int tot1, tot2;
    tot1 = t.minutes +60 * t.hours;
    tot2 = minutes + 60 * hours;
    diff.minutes = (tot2 - tot1) % 60;
    diff.hours = (tot2 - tot1) / 60;
    return diff;
}

我们可以看到上面重载了+,-,但是为什么没有返回引用了:
答曰:返回了被调用函数中的局部变量,所以不能按引用的方式返回!

关键的部分来了,如果你第一次接触重载+=,我想可以对你有一点点帮助吧!因为你可能迷茫如何扩大空间!
还是看看代码吧:

 const String &String::operator+=(const String &right )
 {
    char *tempPtr=sPtr; // hold to be able to delete
    length +=right.length;  // new String length
    sPtr= newchar[ length + 1 ]; // create space
    assert(sPtr!= 0);//terminate if memory not allocated
    strcpy(sPtr,tempPtr); // left part of new String
    strcat(sPtr,right.sPtr);// right part of new String
    delete [ ]tempPtr;   // reclaim old space
    return*this;          // enables cascaded calls
}

正如你说看到了,重载+=时,需要重新开辟一个str1.length+str2.length+1大小的空间。

其实也没有什么好说的吧!

你可能感兴趣的:(C++)