实现了一个字符串类Str
.,然后重载运算符+
和运算符=
。在调用这两个构造函数的时候程序报错HEAP ERROR DETECTED。
类的实现如下
class String
{
public:
String(const char* s="");
String(const String& other);
~String();//拷贝构造函数
String& operator=(const String& other); //赋值运算符重载
String& operator=(const char* s);//为字符串类直接赋值
friend String operator+(String& s1, String& s2);
void Display() const;//显示
void Copy(const char* str);
private:
char* s_;
};
#include "String.h"
#include<cstring>
#include<iostream>
using namespace std;
void String::Copy(const char* str)
{
s_ = new char(strlen(str) + 1);
strcpy_s(s_, strlen(str) + 1, str);
}
String::String(const char* s)
{
Copy(s);
cout << "Create " << s_ <<" by constructor" << endl;
}
String::String(const String& other)
{
//delete s_;
Copy(other.s_);
cout << "Copy Constructor " << s_ << endl;
}
String::~String()
{
cout << "Delete " << s_ << endl;
delete s_;
}
void String::Display() const
{
cout << s_ << endl;
}
String& String::operator=(const char* s)
{
delete s_;
Copy(s);
return *this;
}
String& String::operator=(const String& other)
{
if (this == &other)
return *this;
delete s_;
Copy(other.s_);
return *this;
}
String operator+(String& s1, String& s2)
{
int n1 = strlen(s1.s_);
int n2 = strlen(s2.s_);
char* tmp = new char[n1 + n2 + 1];
strcpy_s(tmp, n1 + 1, s1.s_);
strcat_s(tmp, n1 + n2 + 1, s2.s_);
return String(tmp);
}
测试代码如下:
#include"String.h"
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
String s1;
s1 = "hello";
s1.name = 1;
String s2(" world");
s2.name = 2;
String s3;
s3 = s1 + s2;
s3.name = 3;
return 0;
}
进一步调试发现,在执行代码s3 = s1 + s2
时,operator+
函数返回一个临时变量,然后通过拷贝构造函数赋值给s3
,随后调用析构函数释放该临时变量,在调用析构函数时报错。
想不明白为什么这里报错,求解释,万分感谢!