分享

数据结构五:字符串String(C++代码)

 慢慢体验人生 2011-10-18

 

数据结构系列均是本人个人搜集和写出来的,若有错误请大家批评指正。(有的是c++,有的是伪代码)

 

1. String

class String

{

public:

       String( const char * str = NULL );

       String( const String & other);

       ~String();

       String & operator=( const String & other);

private:

       char * m_p;

};

 

String::String( const char * str )

{

       if ( NULL == str )

       {

              m_p = new char[1];

              if ( NULL != m_p )

              {

                     *m_p = '\0';

              }

       }

       else

       {

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

              if ( NULL != m_p )

              {

                     strcpy( m_p, str );

              }

       }

}

 

String::String( const String & other )

{

       m_p = new char[strlen(other.m_p)+1];

       if ( NULL != m_p )

       {

              strcpy( m_p, other.m_p );

       }

}

 

String & String::operator=( const String & other )

{

       if ( this != &other )

       {

              delete [] m_p;

              m_p = new char[strlen(other.m_p)+1];

              if ( NULL != m_p )

              {

                     strcpy( m_p, other.m_p );

              }

       }

       return *this;

}

 

String::~String()

{

       delete [] m_p;

}

 

 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多