<分区>
标签 c++
<分区>
#include <stdio.h>
#include <string.h>
struct mystr {
char *str;
mystr(const char *s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
printf("[1]%s\n", s);
}
mystr(const mystr &s) {
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
~mystr() {
delete[] str;
}
void printn() const {
printf("%s\n", str);
}
//mystr& operator+=(const char *s) this line works!
mystr operator+=(const char *s) {
char *old = str;
int len = strlen(str) + strlen(s);
str = new char[len + 1];
strcpy(str, old);
strcat(str, s);
printf("[2]%s,%s,%s\n", old, s, str);
delete[] old;
return *this;
}
};
int main() {
mystr s = "abc";
(s += "def") += "ghi";
// only print s = abcdef
// when put & before operator+=, it prints s = abcdefghi
printf("s = %s\n", s.str);
}
有什么区别 返回 mystr & vs mystr? 我看到 operator+= 被调用了两次,但输出不同。 在 C++ 中返回实例有什么行为?
最佳答案
区别在于您返回的是拷贝还是引用。
有了这个:
mystr operator+=(const char*) {/* some code */ return *this;}
你返回一个this
对象的拷贝。
有了这个:
mystr& operator+=(const char*) {/* some code */ return *this;}
您返回对this
对象的引用。
当您退回拷贝时:
(s += "def") += "ghi";
不将 "ghi"
添加到 s
,而是添加到它的拷贝,保持 s
不变。
您可以让您的 mystr(const mystr &s)
复制构造函数(并且可能是析构函数)也打印出一些东西以查看差异。
关于c++ - 返回引用实例和非引用实例之间有什么区别(return mystr & vs mystr)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59621426/