文章标题

MyString.h

pragma once

include

include

class CMyString
{
public:
// CMyString(void);
~CMyString(void);

CMyString(const char* str = NULL);  
CMyString(const CMyString & another);  
CMyString & operator = (const CMyString & another);  
CMyString operator + (const CMyString & another);  

bool operator > (const CMyString & another);  
bool operator < (const CMyString & another);  
bool operator == (const CMyString & another);  

char& operator[](int idx);  

void dis();  

private:
char* _str;
};
MyString.cpp

include “stdafx.h”

include “MyString.h”

// 默认构造器
CMyString::CMyString(const char* str)
{
if (NULL == str)
{
_str = new char[1];
*_str = ‘\0’;
} else
{
int len = strlen(str);
_str = new char[len + 1];
strcpy_s(_str, len + 1, str);
}
}
// 拷贝构造器
CMyString::CMyString(const CMyString & another)
{
int len = strlen(another._str);
_str = new char[len + 1];
strcpy_s(_str, len + 1, another._str);
}
// 析构函数
CMyString::~CMyString()
{
delete []_str;
}
// 赋值运算符重载
CMyString & CMyString::operator = (const CMyString & another)
{
// 自赋值,出现错误
if (this == &another)
{
return *this;
}
// 先删除自己开辟的空间
delete []_str;
int len = strlen(another._str);
this->_str = new char[len + 1];
strcpy_s(this->_str, len + 1, another._str);
return *this;
}
// 加法运算符重载
CMyString CMyString::operator + (const CMyString & another)
{
int len = strlen(this->_str) + strlen(another._str);
CMyString str;
delete []str._str;
str._str = new char[len + 1];
memset(str._str,0,len + 1);
int len1 = strlen(this->_str) + 1;
strcat_s(str._str, len1, this->_str);
// 源串长度 + 目标串长度 + 结束符
int len2 = strlen(this->_str) + strlen(another._str) + 1;
strcat_s(str._str,len2, another._str);
return str;
}
// ==关系运算符重载
bool CMyString::operator==(const CMyString &other)
{
if(strcmp(this->_str,other._str) == 0)
return true;
else
return false;
}
// >关系运算符重载
bool CMyString::operator>(const CMyString &other)
{
if(strcmp(this->_str,other._str) > 0)
return true;
else
return false;
}
// <运算符重载
bool CMyString::operator<(const CMyString &other)
{
if(strcmp(this->_str,other._str) < 0)
return true;
else
return false;
}
// []运算符重载
char& CMyString::operator[](int idx)
{
return _str[idx];
}
// 打印函数
void CMyString::dis()
{
using namespace std;
for (size_t i = 0; i < strlen(this->_str); i++)
{
cout << _str[i];
}
cout << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值