你好在这里构建我自己的字符串类的一些主要成员函数。
当编译器从friend MyString operator+
函数返回新对象时,它会调用析构函数,然后在delete[] data
中中断;
这是如何看待课程的一部分:
class MyString
{
public:
...
//create a string from a null-terminated array
MyString(const char *cp):data(new char[std::strlen(cp)+1]), data_length(std::strlen(cp))
{
std::copy(cp, cp + std::strlen(cp), stdext::checked_array_iterator<char*>(data, data_length));
data[data_length] = '\0';
}
//copy constructor
MyString(const MyString& str)
:data(new char[str.data_length]),
data_length(str.data_length)
{
std::copy(str.data, str.data + str.data_length,
stdext::checked_array_iterator<char*>(data, data_length));
data[data_length] = '\0';
}
//assignment operator #1
MyString& operator=(const char *cp)
{
if (cp != data)
{
data_length = std::strlen(cp);
delete[] data;//delete the old data
data = new char[std::strlen(cp) + 1];//create new data array
std::copy(cp, cp + std::strlen(cp), stdext::checked_array_iterator<char*>(data, data_length));
data[data_length] = '\0';
}
return *this;
}
//assignment operator #2 with self-assignment check
MyString& operator=(const MyString& str)
{
if (&str != this)
{
data_length = std::strlen(str.data);
delete[] data;//delete the old data
data = new char[str.size() + 1];//create new data array
std::copy(str.data, str.data + str.size(), stdext::checked_array_iterator<char*>(data, data_length));
data[data_length] = '\0';
}
return *this;
}
//destructor
~MyString()
{
//free the array
if (data != nullptr)
{
delete[] data;
}
};
MyString& operator+=(MyString& s)
{
std::copy(s.data, s.data + data_length,
stdext::checked_array_iterator<char*>(data+data_length, data_length));
data[data_length + s.data_length] = '\0';
data_length += s.data_length;
return *this;
}
friend MyString operator+(MyString& s1, MyString& s2)
{
MyString str = s1;
str += s2;
return str;
}
private:
size_t data_length;
char* data;
};
int main()
{
MyString mystr1 = "hello";
MyString s_con = mystr1 + mystr1;
return 0;
}