我正在制作我自己的字符串类并且一切正常,除了一个:我正在尝试重载 operator +=
运算符以便我可以这样做:
string s1 = "Hello", s2 = " World";
s1 += s2;
所以这就是我的尝试:
// In the string class,
string& operator +=(string const& other)
{
using std::strcpy;
unsigned length = size() + other.size() + 1; // this->size() member
char *temp = new char[length]; // function and a "+ 1" for the
// null byte '\0'
strcpy(temp, buffer);
strcpy(temp, other.data());
delete[] buffer;
buffer = new char[length];
strcpy(buffer, temp); // copy temp into buffer
return *this;
}
但是在my program使用上面显示的 main 中的代码时,打印后没有输出。我也没有收到任何错误(甚至没有运行时错误)。为什么会这样,我该如何解决这个实现?
注意:我知道我可以使用 std::string
但我想自己学习如何做。
最佳答案
问题来了:
strcpy(temp, other.data());
您已经将第一个字符串复制到缓冲区中(在上一行中),但是这会用另一个字符串的数据覆盖它。您想要使用 strcat
将其他字符串的数据附加到缓冲区:
strcat(temp, other.data());
正如 Jerry 指出的那样,您的另一个问题是您一开始就没有正确初始化字符串。
顺便说一句,如果你打算使用 strcpy
、strcat
等,你真的应该使用长度限制版本( strncpy
、 strncat
)来避免潜在的缓冲区溢出问题。
关于c++ - 我怎样才能让这个 += 运算符工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17055965/