내 자신의 클래스 문자열을 만들려고합니다. 연산자 오버로딩에 몇 가지 문제가 있습니다.연산자가 자신의 문자열에 대해 오버로드 (+ =, =)
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 (블록).
코드를 디버거와 함께 라인 단위로 isnpecting 할 때 당신은 무엇을 관찰 했습니까? –
"런타임 오류"는 무엇입니까? 그에 따라 질문을 편집하십시오. –
@ aleshka-batman 이러한 연산자를 사용하는 방법을 보여 주어야합니다. 예를 들어 복사 할당 연산자가 분명히 잘못되었습니다. 또한 복사 생성자를 정의해야합니다. –