string类实现(C++)
2024-10-12 10:12:03
class CMyString
{
friend std::ostream& operator<<( std::ostream& os, const CMyString& str);
private:
char* m_pData; // 私有变量保存字符串
public:
CMyString( const char* str = NULL ); // 构造函数
CMyString( const CMyString& str ); // 拷贝构造函数
~CMyString( void ); // 析构函数
CMyString& operator=( const CMyString& str ); // 赋值运算符
CMyString operator+( const CMyString& str ); // 字符串连接
bool operator==( const CMyString& str ); // 判断相等
char operator[]( int idx ); // 数组索引
int getLength(); // 返回长度
};
CMyString::CMyString( const char* str )
{
if ( !str )
{
this->m_pData = ;
}
else
{
this->m_pData = new char[ strlen( str ) + ];
strcpy( this->m_pData, str );
}
} CMyString::CMyString( const CMyString& str )
{
if ( !str.m_pData )
{
this->m_pData = ;
}
else
{
this->m_pData = new char[ strlen( str.m_pData ) + ];
strcpy( this->m_pData, str.m_pData );
}
} CMyString::~CMyString( void )
{
if ( this->m_pData)
{
delete[] this->m_pData;
this->m_pData = ;
}
} CMyString& CMyString::operator=( const CMyString& str)
{
if ( this != &str )
{
delete[] this->m_pData;
if ( !str.m_pData )
{
this->m_pData = ;
}
else
{
this->m_pData = new char[ strlen( str.m_pData ) + ];
strcpy( this->m_pData, str.m_pData );
}
}
return *this;
} CMyString CMyString::operator+( const CMyString& str )
{
CMyString newString;
if ( !str.m_pData )
{
newString = *this;
}
else if ( !this->m_pData )
{
newString = str;
}
else
{
newString.m_pData = new char[ strlen( this->m_pData ) + strlen( str.m_pData ) + ];
strcpy( newString.m_pData, this->m_pData );
strcat( newString.m_pData, str.m_pData );
} return newString; } bool CMyString::operator==( const CMyString& str )
{
if ( strlen(this->m_pData) != strlen( str.m_pData ) )
{
return false;
}
else
{
return strcmp( this->m_pData, str.m_pData ) ? false : true;
}
} char CMyString::operator[]( int idx)
{
if ( idx > && idx < strlen( this->m_pData ) )
return this->m_pData[idx];
} int CMyString::getLength()
{
return strlen(this->m_pData);
} std::ostream& operator<<( std::ostream& os, const CMyString& str )
{
os<< str.m_pData;
return os;
}
最新文章
- android studio入门
- AndroidStudio关联svn并上传代码到svn服务器上
- MyEclipse 选中右侧编辑的文件时自动展开左侧目录树
- [转]LIBSVM-3.18在python环境下的使用
- HBase Shell输入命令无法删除问题解决技巧
- 《Genesis-3D开源游戏引擎--横版格斗游戏制作教程03:碰撞检测》
- 群赛 ZOJ3741(dp) ZOJ3911(线段树)
- js 对url字符转译全解
- Windows服务程序的原理及实现(服务分为WIN32服务和系统服务)
- 关于reportng生成的测试报告不按测试执行顺序的解决办法
- php基础(七)文件
- [iOS Animation]-CALayer 图层树
- 你真的会阅读Java的异常信息吗?
- BZOJ 1486: [HNOI2009]最小圈 [01分数规划]
- unity案例入门(二)(坦克大战)
- mac里用PyCharm中引用MySqlDB始末
- [题解]洛谷P2709 小B的询问
- cmd非运行完再保存,结果显示&;保存同时进行
- Spring Enable* 注解
- Spring Boot开发Web应用