【C++】String类拷贝构造函数——深拷贝普通版和简洁版
来源:互联网 发布:美团外卖数据分析2017 编辑:程序博客网 时间:2024/05/28 18:44
#define _CRT_SECURE_NO_WARNINGS 1#include<iostream>using namespace std;class String{public://构造函数String(char* pStr = ""){if (NULL == pStr){_pStr = new char[1];*_pStr = '\0';}else{_pStr = new char[strlen(pStr) + 1];strcpy(_pStr, pStr);}}////拷贝构造函数1 简洁版//String(const String& pStr)//:_pStr(NULL)//{//String temp(pStr._pStr);//swap(_pStr, temp._pStr);//}//拷贝构造函数2 普通版String(String& pStr):_pStr(new char[strlen(pStr._pStr)+1]){strcpy(_pStr, pStr._pStr);}////赋值运算符重载1//String& operator=(const String& pStr)//{//if (this != &pStr)//{//String temp(pStr._pStr);//swap(_pStr, temp._pStr);//}//return *this;//}//赋值运算符重载2String& operator=(const String& pStr){if (this != &pStr){//防止new开辟内存失败,丢失原来内存char* ptr = new char[strlen(pStr._pStr) + 1];strcpy(ptr, pStr._pStr);delete[]_pStr;_pStr = ptr;}return *this;}//析构函数~String(){if (NULL != this){delete[]_pStr;_pStr = NULL;}}friend ostream& operator<<(ostream& _cout, const String& pStr);private:char* _pStr;};ostream& operator<<(ostream& _cout, const String& pStr){_cout << pStr._pStr;return _cout;}void Funtest(){String s1("hehe");cout << s1 << endl;String s2;s2 = s1;cout << s2 << endl;String s3(s1);cout << s3 << endl;}void Funtest2(){String s1("hello");String s2(s1);cout << s1 << endl;cout << s2 << endl;cout << "##################" << endl;String s3("world");cout << s3 << endl;s3 = s1;cout << s3 << endl;cout << "##################" << endl;}int main(){Funtest2();system("pause");return 0;}
阅读全文
0 0
- 【C++】String类拷贝构造函数——深拷贝普通版和简洁版
- 【C++】简单实现String类--深拷贝的普通版本和简洁版本
- 写String类的普通构造函数,析构函数,拷贝构造函数和赋值函数
- string类,浅拷贝,深拷贝(简洁版),写时拷贝
- 用String类的实验,说明拷贝构造函数、重载等号赋值函数、和普通构造函数的区别
- C++拷贝构造函数——深拷贝/浅拷贝
- 编写String类的普通构造函数、拷贝构造函数、析构函数、赋值函数
- 【C++】String类拷贝构造函数——浅拷贝优化的三种方式(引用计数)
- 【C++基础】——拷贝构造函数的浅拷贝和深拷贝
- String类:构造函数,拷贝构造函数
- 类String的普通构造、拷贝构造函数与赋值函数
- 【C++】String拷贝(包含深拷贝浅拷贝)以及拷贝构造函数中几种调用的情况
- 5.c++-拷贝构造函数(深拷贝,浅拷贝)
- c++_拷贝构造函数/浅拷贝/深拷贝
- C++——拷贝构造函数
- String类---深拷贝,简洁深拷贝,引用计数拷贝,写时拷贝
- string 构造 拷贝 和析构函数
- 拷贝构造函数(深拷贝和浅拷贝)
- usaco section1.2 Transformations
- Java十二平均律判断
- JNDI
- HDU-1503 Advanced Fruits
- jdbcTemplate操作数据库
- 【C++】String类拷贝构造函数——深拷贝普通版和简洁版
- 1到n的所有排列情况
- 搜索-O
- 任务二(Html Css简单学习与知识整理)
- org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may
- UI设计师注意,网站头图的10个黄金法则
- 我的第一篇博客
- Magento 2中文手册教程
- 网站seo优化需要注意的关键要点