浅拷贝(在进行其中一个对象的运算时开辟新的空间)
2015-06-07 02:14
417 查看
如图变换,且对于指向同一空间的String进行计数
代码如下:
#include <iostream> using namespace std; class String; //提前声明 class String_rep //定义类String_rep { friend class String; //友元 public: String_rep(const char *str=NULL):use_count(0) //构造 { if(str == NULL) { m_data = new char[1]; m_data[0] = '\0'; } else { m_data = new char[strlen(str)+1]; strcpy(m_data,str); } } String_rep(const String_rep &r); //拷贝构造 String_rep& operator=(const String_rep &r); //赋值函数 ~String_rep() { delete []m_data; } public: void increment() //计数器加一 { use_count++; } void decrement() //若计数器为零则释放 { if(--use_count == 0) { delete this; } } int get_use_count()const //计数器 { return use_count; } void Show()const //显示 { cout<<m_data<<endl; } private: //私有成员 char *m_data; long use_count; }; class String //定义类String { public: String(const char *str=NULL):rep(new String_rep(str)) //构造 { rep->increment(); } String(const String &s):rep(s.rep) //拷贝构造 { rep->increment(); } String& operator=(const String &s) //赋值函数 { if(this != &s) //若为同一字符串 { rep->decrement(); rep = s.rep; rep->increment(); } return *this; //反之 } ~String() //析构 { rep->decrement(); } public: void Show()const //显示 { rep->Show(); } void to_upper() //变为大写 { String_rep *new_rep = new String_rep(rep->m_data); //新的指针 rep->decrement(); //原计数器减一 rep = new_rep; //指向新的空间 rep->increment(); //现计数器加一 char *pch = rep->m_data; //确定指向 while(*pch != '\0') //变成大写 { *pch -= 32; pch++; } } private: String_rep *rep;//句柄 }; void main() { String s1("abcd"); String s2 = s1; String s3; s3 = s2; s1.to_upper();//将s1的小写变大写 s1.Show(); //ABCD s2.Show(); //abcd s3.Show(); //abcd }
如果代码有不足的地方希望大家指出~谢谢。
相关文章推荐
- eclipse快捷键
- xcode常用快捷键
- SourceTree基本操作
- http接口开发请求参数签名实用工具类
- IIS7.5发布delphi编写的ISAPI
- xcode iOS 模拟器 textField 鼠标点击后键盘不显示
- 由php的单例模式到php对象的创建方式
- Jquery Ajax遍历list
- Best Time to Buy and Sell Stock IV
- 设备接到apns发来的通知
- zen coding缩写语法
- MVC2.0==>MVC3.0
- Java面向对象小记(3)
- [.net 面向对象编程基础] (14) 重构
- 二维数组的创建
- JPA常用注解
- 2015 Astar Contest - Round 2A 题解
- Unable to find vcvarsall.bat解决办法
- Js 冒泡事件阻止
- Bitcoin学习篇之---Script