Stringクラスの練習
4121 ワード
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
String(const char* str = NULL)
{
m_data = strcpy(new char[strlen(str?str:"")+1],str?str:"");
}
~String()
{
if(m_data)
delete[] m_data;
}
String(const String& that)
{
m_data=strcpy(new char[strlen(that.m_data)+1],that.m_data);
}
String& operator=(const String& that)
{
if(&that != this)
{
//
//delete[] m_data;
//m_data = strcpy(new char[strlen(that.m_data)+1],that.m_data);
//
//char* temp = new char[strlen(that.m_data)+1]);// , ,
//delete[] m_data;
//m_data = strcpy(temp,that.m_data);
//
String str(that);
swap(m_data,str.m_data); //
}
return *this;
}
char* c_str() const
{
return m_data;
}
private:
char* m_data;
};
int main()
{
String s1("Hello Word");
cout << s1.c_str() << endl;
String s2(s1);
cout << s2.c_str() << endl;
return 0;
}