运算符重载 (+=,=) 用于自己的字符串
Operators overloading (+=,=) for own strings
我正在尝试创建自己的类字符串。我在运算符重载方面遇到了一些问题。
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(块)。
operator+=
和operator=
通常返回对this
的引用。
当前,您正在按值返回,该值使用编译器生成的复制构造函数。该构造函数获取数据缓冲区指针value
这是崩溃的根本原因:指针上的多个delete[]
不会有好结果!
从研究"3 法则"开始,构建复制构造函数和赋值运算符,修复重载运算符返回类型,然后从那里继续。
至少在将对象分配给自身时,复制赋值运算符包含一个严重的错误,因为起初它被删除了。此外,运算符应返回对自己的引用。
好吧,可以通过以下方式定义运算符
My_string & My_string::operator +=( const My_string &r_argument )
{
if ( r_argument.value[0] )
{
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 = temp_value;
}
return *this;
}
和
My_string & My_string::operator =( const My_string &r_argument )
{
if ( this != &r_argument )
{
char *temp_value = value;
size_t n = strlen( r_argument.value );
if ( n != strlen( value ) )
{
temp_value = new char[ n + 1 ];
}
else
{
value = nullptr;
}
strcpy( temp_value, r_argument.value );
delete [] value;
value = temp_value;
}
return *this;
}
考虑到您还需要显式定义复制构造函数。
相关文章:
- 没有为自己的结构调用列表推回方法
- 使用在用于SFINAE的void_t中具有参数的方法
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 用于AVX的ln(x)的实现,m256
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 用于窗口的 HID 终端
- 用于C++的静态二进制检测或二进制重写工具和框架
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++从对象自己的类中删除对象
- 使用 std::optional,而不是自己的结构
- 子轴围绕父轴而不是他自己的轴旋转
- 用于 ASCII 的环绕式 C++
- 运算符重载 (+=,=) 用于自己的字符串
- javascript中的静态私有变量用于自己的库
- C++:将mem乐趣用于自己的结构
- 可以将std::find函数用于我们自己的类
- Can运算符<<用于设计我们自己的输出显示方式
- Push _back用于您自己的STL容器c++
- 返回的结构调用它自己的析构函数,用于销毁分配的对象