首页 新闻 赞助 找找看

C++中在类String中重载+=的问题

0
悬赏园豆:50 [已关闭问题] 关闭于 2013-05-11 22:51
 1 const String &String::operator+=(const String &right )
 2   {
 3     char *tempPtr=sPtr;               // hold to be able to delete
 4     length +=right.length;           // new String length
 5     sPtr= newchar[ length + 1 ];     // create space
 6     assert(sPtr!= 0);  // terminate if memory not allocated
 7     strcpy(sPtr,tempPtr);           // left part of new String
 8     strcat(sPtr,right.sPtr);        // right part of new String
 9     delete [ ]tempPtr;              // reclaim old space
10     return*this;                    // enables cascaded calls
11   }

这是对C++的string的扩展类String的一个+=重载函数,假设其他函数都健全。

如果main()中有一句

String str1("he"), str2("llo");
str1+=str2;

下面是我的想法和问题:

1 str1的sPtr变成了内存中的另一个区域,储存着"hello";length则只是从2改成了5
2 函数体内执行的过程就是直接修改str1,最后返回*this指针,这有必要吗?我觉得没必要啊
3 我先认为其他的是对的,但是const String &型的变量传给str1,以后它不就不能再改变了?
wkl7123的主页 wkl7123 | 初学一级 | 园豆:154
提问于:2013-05-11 18:54
< >
分享
所有回答(1)
0
*this指针是返回给函数的(对所有函数都这样),str1的change在+=算子的生命周期中已经完成了。const 修饰是为了防止返回值被作为左值
wkl7123 | 园豆:154 (初学一级) | 2013-05-11 22:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册