gpt4 book ai didi

c++ - 重写 += 运算符 C++

转载 作者:行者123 更新时间:2023-11-30 00:57:21 26 4
gpt4 key购买 nike

更新:为 str1 的新数据分配内存。还是内存错误。

我正在尝试为我创建的字符串类重写 += 方法。

Class mystring{

public:
friend void operator+=(mystring& str1, const mystring& str2){
mystring temp;

delete[] temp.data;
temp.length = str1.length + str2.length;
temp.data = new char[temp.length + 1];

strcpy(temp.data, str1.data);
strcat(temp.data, str2.data);

delete[] str1.data;
str1.length = temp.length;

strcpy(str1.data, temp.data);

}

private:
char *data;
int length;

}

然后在主类中:

mystring str1("hi");
mystring str2("matt");

str1 += str2;
cout << str1 << endl;

此功能正常运行,但在运行 valgrind 时出现内存错误。我无法弄清楚为什么会这样。如果有人能给我任何提示,那就太棒了。

谢谢

最佳答案

首先,你的意思不是:

 strcat(str1.data, str1.data);

但是:

 strcat(str1.data, str2.data);

其次,您希望 str2.data 去哪里?这是一个内存涂鸦,因此是 valgrind 错误。惊讶它不只是崩溃。

您需要为组合长度重新分配足够的存储空间,在将其重新分配给新存储空间之前复制原始字符串和空闲的 str1.data

基于更新后的帖子:

friend void operator+=(mystring& str1, const mystring& str2)
{
// Not using a temp mystring here, as the temp never really maintains its state as a mystring
// I am assuming length is the length of the string, not the storage. Not the best design if you consider resizing the the string to less than the storage
int newStringLength = str1.length + str2.length;
char* newStorage = new char[newStringLength + 1];

strcpy(newStorage, str1.data);
// strcat has to scan from the start of the string; we do not need to.
strcpy(newStorage + str1.length, str2.data);

delete[] str1.data;

str1.length = newStringLength ;
str1.data = newStorage;

// Haven't though about the case where str2 is an alias for str1.
}

关于c++ - 重写 += 运算符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8395044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com