#ifndef STRING_H
#define STRING_H
#include <iostream>
#include <cstring>
using namespace std;
class String
{
char* str;
public:
//构造
String(const char* str = NULL)
{
this->str = new char[strlen(str)+1];
strcpy(this->str,str);
cout << "带参构造String(const char* str)" << endl;
}
String(void)
{
str = new char[1];
str[0] = '\0';
cout << "无参构造String(void)" << endl;
}
//拷贝构造
String(const String& that)
{
str = new char[strlen(that.str)+1];
strcpy(str,that.str);
cout << "拷贝构造String(String& that)" << endl;
}
//赋值
String& operator = (const String& that)
{
cout << "赋值构造String& operator = (const String& that)" << endl;
if(this != &that)
{
delete[] str;
this->str = new char[strlen(that.str)+1];
strcpy(str,that.str);
}
return *this;
}
//析构
~String(void)
{
delete[] str;
cout << "析构" << endl;
}
void show(void)
{
cout << this->str << endl;
}
};
#endif//STRING_H
C++string类的手动实现
最新推荐文章于 2023-08-10 18:26:32 发布