运算符重载 (+=,=) 用于自己的字符串

Operators overloading (+=,=) for own strings

本文关键字:用于 自己的 字符串 运算符 重载      更新时间:2023-10-16

我正在尝试创建自己的类字符串。我在运算符重载方面遇到了一些问题。

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;
}

考虑到您还需要显式定义复制构造函数。