String类实现
作者:互联网
#include <iostream>
#include<string.h>
using namespace std;
class String{
public:
String(const char* cstr = 0);
String(const String& cstr);
String& operator=(const String& str);
~String();
char* get_c_str() const {return my_data;}
private:
char* my_data;
};
inline String::String(const char* cstr = 0)
{
if(cstr){
my_data = new char[strlen(cstr) + 1];
strcpy(my_data, cstr);
}
else{
my_data = new char[1];
*my_data = '\0';
}
}
inline String::~String()
{
delete[] my_data;
}
inline String::String(const String& cstr)
{
my_data = new char[strlen(cstr.my_data) + 1];
strcpy(my_data, cstr.my_data);
}
inline String& String::operator=(const String& str)
{
if(&str == this)
return *this;
delete[] my_data;
my_data = new char[strlen(str.my_data) + 1];
strcpy(my_data, str.my_data);
return *this;
}
标签:const,String,实现,data,char,cstr,my 来源: https://blog.csdn.net/Ayy_forever/article/details/121243951