class String
{
private:
char * str;
public:
//String()
//{
// str = NULL;
//};//无参的构造函数
String(const char * p = NULL)//带参的构造函数,需要自己定义默认构造函数
{
if (p == NULL)
{
str = new char[1];//对象里的指针指向了开辟的堆
*str = '\0';
}
else
{
int n = strlen(p) + 1;
str = new char[n];
strcpy_s(str, n, p);
}
}
String(const String &p)
{
int n = strlen(p.str) + 1;//强拷贝
str = new char[n];
//str = p.str;//浅拷贝,p.str与str指向同一块堆
strcpy_s(str, n, p.str);
}
~String()//动态的获得空间需要delete
{
delete[]str;
}
void PrintString()
{
if (str != NULL)
cout << str << endl;
}
String & operator=(const String &x)
{
if (str != x.str)
{
delete[]str;
//str=x.str 系统默认浅拷贝 会造成内存泄露和析构两次
int n = strlen(x.str) + 1;//深赋值
str = new char[n];
strcpy_s(str, n, x.str);
}
return *this;
}
String operator+(const String &x)const
{
int n = strlen(x.str);
n += strlen(str)+1;
char *p = new char[n];
strcpy_s(p, n, str);
strcat_s(p,n, x.str);
return String(p);
}
const char operator[] (const int x)const //可读
{
return str[x];
}
// int value;
char & operator[](int x) //str[2]被引用 即传回去的是ar[2]的引用
{
//只要能修改this不就行了
//怎么返回一个变量?
//this->value = x;
return str[x];
}
};
C++字符串类
最新推荐文章于 2022-08-21 10:35:40 发布