#include <iostream>
using namespace std;
class String
{
private:
char *pc;
public:
//注意const的使用
String(const char *pcStr = NULL) //默认参数
{
cout<<"construct"<<endl;
if (NULL != pcStr)
{
pc = new char[strlen(pcStr) + 1];
memcpy(pc, pcStr, strlen(pcStr) + 1);
}
else /* 出现空指针的情况 */
{
pc = new char[1];
pc[0] = '\0';
}
}
~String()
{
cout<<"destroy"<<endl;
if (NULL != pc)
{
delete pc;
pc = NULL;
}
}
String(const String &str)
{
cout<<"copy construct"<<endl;
if (NULL != str.pc)
{
pc = new char[strlen(str.pc) + 1];
memcpy(pc, str.pc, strlen(str.pc) + 1);
}
}
String& operator=(const String& rhs)
{
cout<<"======"<<endl;
if (&rhs == this) /* 防止自己拷贝自己 */
{
return *this;
}
/* 删除被赋值对象中指针变量的内存空间,防止内存泄露 */
if (NULL != pc)
{
delete pc;
pc = NULL;
}
pc = new char[strlen(rhs.pc) + 1];
memcpy(pc, rhs.pc, strlen(rhs.pc) + 1);
return *this;
}
void print()
{
if (NULL != pc)
{
printf("%s\n", pc);
}
}
};
int main(int argc, char** argv)
{
char *s = "hello";
String str(s);
str.print();
String str2;
str2.print();
str2 = str;
str2.print();
String str3(str2);
str3.print();
return 0;
}
C++ String面试题
最新推荐文章于 2022-11-04 17:02:47 发布
本文介绍了一个C++自定义字符串类的实现,重点展示了构造函数、析构函数、拷贝构造函数及赋值运算符重载的细节,特别是深拷贝的处理方式,以避免内存泄漏。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Stable-Diffusion-3.5
图片生成
Stable-Diffusion
Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率
197

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



