【发布时间】:2017-02-03 13:20:31
【问题描述】:
我正在尝试创建自己的类字符串。 我在运算符重载方面遇到了一些问题。
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)。
【问题讨论】:
-
使用调试器逐行检查代码时,您观察到了什么?
-
什么“运行时错误”?请相应地编辑您的问题。
-
@aleshka-batman 您应该展示如何使用这些运算符,例如复制赋值运算符显然是错误的。您还必须定义复制构造函数。
-
你的操作符
+=和=返回 copy 但你没有你的 copy-constructor -
@Tomáš M 已编辑。
标签: c++ operator-overloading new-operator delete-operator