#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面试题
最新推荐文章于 2025-04-06 12:20:20 发布