#include<iostream>
#include<cstring>
using namespace std;
//template<class T>
class myString
{
private:
char *str;
public:
myString() {
str = new char[1];
str[0] = '\0';
}
myString(const char* pStr)
{
if(pStr == NULL)
{
str = new char[1];
str[0] = '\0';
}else
{
str = new char[strlen(pStr) + 1];
strcpy(str, pStr);
}
}
myString(const myString& tmp)
{
str = new char[strlen(tmp.str)+1];
if(str != NULL) {
strcpy(str, tmp.str);
}
else {
str = NULL;
}
}
~myString()
{
delete str;
str = NULL;
}
myString &operator =(const myString &other)
{
if(this == &other)
return *this;
delete str;
str = new char[strlen(other.str)+1];
if(str != NULL) {
strcpy(str, other.str);
}
else {
str = NULL;
}
return *this;
}
};
int main()
{
return 0;
}

本文介绍了一个简单的自定义字符串类myString的实现过程,包括构造函数、析构函数、拷贝构造函数及赋值运算符重载等关键成员函数的设计与实现。通过对这些成员函数的详细说明,展示了如何在C++中正确管理动态分配的内存。

被折叠的 条评论
为什么被折叠?



