mystring类的实现
来源:互联网 发布:用matlab求矩阵方程 编辑:程序博客网 时间:2024/06/10 01:27
mystring.h
文件
#ifndef _CMYSTRING_H_#define _CMYSTRING_H_#include <iostream>#include <cstring>class CMyString{public: //default ctor CMyString(const char *s = nullptr) { if (!s) { _data = new char[1]; *_data = '\0'; return; } _data = new char[strlen(s) + 1]; strcpy(_data, s); } //copy ctor CMyString(const CMyString &other) { _data = new char[strlen(other._data) + 1]; strcpy(_data, other._data); } //dtor ~CMyString() { delete [] _data; } //assign operator CMyString& operator=(const CMyString &other) { if(this == &other) return *this; delete _data; _data = new char[strlen(other._data) + 1]; strcpy(_data, other._data); return *this; } friend std::ostream& operator<<(std::ostream &os, const CMyString &s) { os << s._data; return os; } private: char *_data;};#endif
main.cpp
文件
#include <iostream>#include "mystring.h"using namespace std;int main(int argc, char *argv[]){ CMyString str1; CMyString str2("hello,world"); CMyString str3(str2); CMyString str4("hi,world"); str1 = str3 = str4; cout << str1 << " " << str2 << " " << str3 << " " << str4 << endl; return 0;}
异常安全性
考虑赋值运算符中new会产生异常,为了写出异常安全性的代码,上面的代码有两种修改方案:
1. 先new,成功之后再delete掉,不成功则返回原来的状态
2. 先产生一个暂时的栈实例,然后交换两者的数据成员(字符指针),当跳出作用域后,栈实例销毁会销毁原来的数据成员
方案1
CMyString& operator= (const CMyString& other){ if(this == &other) return *this; char *old_data = _data; _data = new char[strlen(other._data) + 1]; if (!_data) return *this; delete old_data; strcpy(_data, other._data); return *this;}
方案2
CMyString& operator=(const CMyString &other){ CMyString tmp_str(other); char *tmp_data = tmp_str._data; tmp_str._data = _data; _data = tmp_data; return *this;}
阅读全文
0 0
- MyString类的实现
- mystring类的实现
- 自定义字符串类MyString的C++实现
- C++ MyString类的简单实现
- string类的实现(mystring)
- MyString的实现
- MyString类实现
- 实现自己的mystring.h
- 实现MyString类(二)—MyString.cpp实现
- 【15】实现一个MyString类
- C++之实现MyString类
- C++ 自定义实现MyString类
- C++之实现MyString类
- MyString类的实现--C++ primer plus 读书笔记
- 第三课--之一(对象)实现MyString类的作业
- 实现MyString类(一)—类声明mystring.h
- mystring实现
- MyString实现
- 剑指offer——面试中的各项能力
- 安卓——套接字Socket通信(未完)
- CentOS6.7安装独立版Spark
- java 设计模式之工厂方法模式
- 1054. 求平均值 (20)
- mystring类的实现
- CEF:MFC 对话框 Demo(VS2013)
- 关于CSS 伪类及伪元素
- 【Docker安装】- Ubuntu14.04中安装最新版的Docker
- 斐波拉契数列
- 错误Error:Could not get unknown property 'GROUP' for object of type org.gradle.api.publication.maven.i
- HDOJ 2602 Bone Collector(0-1背包)
- git
- jquery中的选择器