编写类 String 的构造函数、析构函数和赋值函数
来源:互联网 发布:陈小春新拍电视剧网络 编辑:程序博客网 时间:2024/06/05 03:47
#include <iostream>#include<string>using namespace std;class String{public: friend ostream &operator<<(ostream& os, String& s); //这个版本需要考虑用一个赋值String str1(str2); //当str2为空字符串,调用拷贝构造函数时strlen不能求空字符串的值,导致 //程序崩溃问题 //String() //默认构造函数 // :_str(NULL) //{ // cout << "String()" << endl; //} //String() // :_str (new char[1]) //{ // cout << "String()" << endl; // *_str = '/0'; //// *_str = "/0"; //} //String(const char * s) // :_str (new char[strlen(s)+1]) //{ // cout << "String(const char *s)" << endl; // strcpy(_str, s); //} //将默认构造和构造函数合并 String(const char * s="") :_str (new char[strlen(s)+1]) { cout << "String(const char *s)" << endl; strcpy(_str, s); } String(const String &s) //拷贝构造传参必须是引用 :_str(new char[strlen(s._str)+1] ) //并未考虑空指针传给strlen的问题 { cout << "String(const String &s)" << endl; strcpy(_str,s._str); } //String & operator=(const String &s) //{ // cout << "String & operator=(const String &s)" << endl; // if (s._str != _str) //如果不考虑自赋值问题,可能导致自身内容被销毁 // { // delete[]_str; // _str = new char[strlen(s._str) + 1]; // strcpy(_str, s._str); // } // return *this; //} //现代写法 String & operator=( String s) //如果是引用会导致原来申请的堆空间未释放 { cout << "String & operator=(const String &s)" << endl; std::swap(_str, s._str); //s是实参的一份临时拷贝,所以出了这个函数作用域,会自行销毁 return *this; } ~String() { cout << "~String()" << endl; if (_str != NULL) { delete[]_str; } }private: char* _str;};ostream &operator<<(ostream& os, String& s){ os << s._str; return os;}int main(){ //string str = "abcdef"; //string str1 = str; String str1("abcdef"); //String str2(str1); String str3 ; str3 = str1; cout << str1 << endl; cout << str3 << endl; //cout << str2 << endl; //cout << str1 << endl; return 0;}
总结:
在实现时要考虑内存泄漏问题,在实现赋值时非现代版本考虑自赋值问题所带来的后果,以及实现默认构造函数将指针置空,会带来什么后果,以及什么时候该用引用,什么时候不该用。以及要注意的是strlen不能传一个空指针让它去求字符串的长度等等。
0 0
- 编写类String的构造函数、拷贝构造函数、析构函数和赋值函数
- 编写类String 的构造函数、拷贝构造函数、析构函数和赋值函数
- 网易游戏笔试题:编写string类的构造函数、拷贝构造函数、赋值构造函数和析构函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数,析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 如何正确编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String 的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 编写类String的构造函数、析构函数和赋值函数
- 待补2017.3.12 uva11235
- GitHub 上README.md语法
- linux软件包管理(RPM)简单介绍
- 第五、六、七章
- 职场35岁现象:请别浪费你30岁前的时光
- 编写类 String 的构造函数、析构函数和赋值函数
- Google首席科学家谈Google是怎么做深度学习的
- JAVA使用GNU的Gettext后端国际化
- bzoj1500 [NOI2005]维修数列
- 第八章
- 自适应图像分辨率
- Crisis of HDU
- Jeston TX1配置Caffe教程-从裸板开始
- OneNote2016安装代码高亮插件