首页 > 学院 > 开发设计 > 正文

文章标题

2019-11-08 20:03:52
字体:
来源:转载
供稿:网友

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; }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表