首页 > > > C++中在类String中重载+=的问题
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;
下面是我的想法和问题:
1str1的sPtr变成了内存中的另一个区域,储存着"hello";length则只是从2改成了5
2 函数体内执行的过程就是直接修改str1,最后返回*this指针,这有必要吗?我觉得没必要啊
3 我先认为其他的是对的,但是const String &型的变量传给str1,以后它不就不能再改变了?
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1747/viewspace-3165488/ ,如需转载,请注明出处,否则将追究法律责任。