从string类实现C++类的四大函数:
有参构造,拷贝构造,赋值构造,析构函数
#include<iostream>
#include<cstring>
using namespace std;
class String
{
char* c_str;
public:
String(const char* str = NULL)
{
if(NULL == str)
{
c_str = new char[1];
*c_str = '\0';
return ;
}
c_str = new char[strlen(str)+1];
strcpy(c_str,str);
}
String(const String& str)
{
c_str = new char[strlen(str.c_str)+1];
strcpy(c_str,str.c_str);
}
String& operator = (const String& str)
{
if(this != *str)
{
String temp(str);
strcpy(c_str,temp.c_str);
}
}
~String(void)
{
delete[] c_str;
}
void show(void)
{
cout << c_str << endl;
}
}
int main()
{
String str("hehe"),str1;
str.show();
String str2 = str1 = str;
str1.show();
}