自己実現stringクラス

9676 ワード

mystring.h
 1 #pragma once

 2 

 3 class mystring

 4 {

 5 public:

 6     mystring( const char *str=NULL);

 7     mystring(const mystring  &others);

 8     

 9     mystring  &operator = (const mystring & others);

10     virtual ~mystring(void);

11 

12     void disply();

13    

14 private:

15     char *m_data;

16 

17 

18 };

 
mystring.cpp
 1 mystring::mystring( const char *str/*=NULL*/ )

 2 {

 3     

 4     m_data = new char [strlen(str)+1];

 5 

 6 

 7     if(!m_data)

 8     {

 9         

10         return ;

11     }

12 

13     strcpy(m_data,str);

14 

15 }

16 

17 mystring::mystring( const mystring &others )

18 {

19 

20     m_data = new char [strlen(others.m_data)+1];

21 

22 

23     if(!m_data)

24     {

25 

26         return ;

27     }

28 

29     strcpy(m_data,others.m_data);

30 }

31 

32 mystring::~mystring(void)

33 {

34 

35     if(m_data)

36     {

37         delete [] m_data;

38         m_data = NULL;

39     }

40 }

41 

42 void mystring::disply()

43 {

44 

45     cout<<m_data<<endl;

46 }

47 

48 mystring  & mystring::operator=( const mystring & others )

49 {

50 

51    if(this== &others)

52    {

53      return *this;

54    }

55    

56 

57    if(m_data!=NULL)

58    {

59        delete  []m_data;

60    }

61 

62    m_data = new char [strlen(others.m_data)+1];

63    strcpy(m_data,others.m_data);

64    return *this;

65 

66 }

67 

68 

69 int _tmain()

70 

71 {

72 

73 

74     mystring s("sdaadssa");

75 

76     mystring p("dasda");

77 

78 s = p;

79 

80     s.disply();

81     return 0;

82 

83 }