String的构造函数拷贝构造函数
2015-12-24 09:10
316 查看
#include<iostream> using namespace std; class String { private: char *m_Str; protected: public: String(const char *str = NULL) { if (str == NULL) { m_Str = new char[1]; *m_Str = '\0'; } else { int size = strlen(str); m_Str = new char[size + 1]; strcpy(m_Str, str); } } String(const String &other)//拷贝构造函数 { int length = strlen(other.m_Str); m_Str = new char[length + 1]; strcpy(m_Str, other.m_Str); } String& String::operator =(const String &other) { if (this == &other)//当地址相同时,直接返回; return *this; delete[] m_Str;//当地址不相同时,删除原来申请的空间,重新开始构造; int length = strlen(other.m_Str); m_Str = new char[length + 1]; strcpy(m_Str, other.m_Str); return *this; } ~String() { delete[]m_Str; } friend ostream &operator<<(ostream &out,String &s) { out << s.m_Str; return out; } }; int main(int argc, char * argv[]) { String s("abc"); cout << s << endl; return 0; }
相关文章推荐
- 天声人語 20151224 犬も吠える?大気汚染
- 一个c程序的步骤
- StackOverflow程序员推荐:每个程序员都应读的30本书
- 集团信息化之路—电子採购软件与现有库存及財务软件数据对接的探讨
- 通过VBS编写自动输入账号和密码、自动登录程序的脚本
- Polya定理
- libevent很好的翻译与解析
- git的基本介绍(windows)
- SQL Server 2008 清空删除日志文件
- linux下 配置JDK环境变量
- rac 中添加控制文件冗余
- Ubuntu安装SourceInsight说明
- linux的常用易忘命令
- 纯菜鸟逐步认识SVN
- 数据抓取之性能优化第一弹
- VIM常用命令
- 圣斗士星矢 斗士之魂
- Android Zxing 二维码扫码性能优化
- dubbo_负载均衡算法_一致性算法
- Eclipse 中包结构展开有两种方式