编写String类的构造函数,析构函数,赋值函数
#include <iostream>
using namespace std;
class String
{
public:
String(const char* str=NULL);
String(const String& other);
~String(void);
String & operator =(const String& other);
const char* getString() const;
private:
char* m_data;
};
String::~String(void)
{
delete [] m_data;
}
String::String(const char *str)
{
if (str==NULL)
{
m_data=new char[1];
*m_data='\0';
}
else
{
int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data, str);
}
}
String::String(const String& other)
{
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data, other.m_data);
}
String& String::operator=(const String& other)
{
if (this==&other)
{
return *this;
}
delete [] m_data;
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data, other.m_data);
return *this;
}
const char* String::getString() const
{
return m_data;
}
int main()
{
String str("hello");
String str1(" meng");
String str2(str1);
String str3(" jun.");
String str4(str3);
String str5=str4;
cout<<str.getString()<<str2.getString()<<str5.getString()<<endl;
return 0;
}