我正在尝试创建自己的类字符串。
我在运算符重载方面遇到了一些问题。
My_string.h
#include <cstring>
#include <iostream>
class My_string
{
private:
char *value;
public:
My_string();
My_string(char *);
~My_string();
My_string operator +=(const My_string&);
My_string operator =(const My_string&);
void show()const;
};
My_string.cpp
#include "stdafx.h"
#include "My_string.h"
My_string::My_string()
{
value = new char[1];
strcpy(value, "");
}
My_string::My_string(char * r_argument)
{
value = new char[strlen(r_argument) + 1];
strcpy(value, r_argument);
}
My_string::~My_string()
{
delete[]value;
}
My_string My_string::operator+=(const My_string &r_argument)
{
char * temp_value = new char[strlen(value) + strlen(r_argument.value) + 1];
strcpy(temp_value, value);
strcat(temp_value,r_argument.value);
delete[]value;
value = new char[strlen(value) + strlen(r_argument.value) + 1];
strcpy(value, temp_value);
delete[]temp_value;
return *this;
}
void My_string::show() const
{
std::cout << value << std::endl;
}
My_string My_string::operator =(const My_string & r_argument)
{
delete[] value;
value = new char[strlen(r_argument.value)+1];
strcpy(value, r_argument.value);
return *this;
}
如何重载+ =和=运算符?它们均会导致运行时错误。我需要所有人都处于动态分配的内存中。
调试断言失败!
...
表达式:_CrtisValidHeapPointer(block)。
最佳答案
operator+=
和operator=
通常返回对this
的引用。
当前,您正在使用编译器生成的副本构造函数按值返回。该构造函数获取了数据缓冲区指针value
,这是导致崩溃的根本原因:指针上的多个delete[]
不能很好地结束!
首先研究“ 3条规则”,构建副本构造函数和赋值运算符,修复重载的运算符返回类型,然后从那里继续。
关于c++ - 运算符重载(+ =,=)自己的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42025303/