条款28 避免返回handles指向对象内部成分
2015-09-09 21:16
260 查看
/*条款28 避免返回handles指向对象内部成分*/ /*handles: 指针,引用,迭代器*/ //设计一个矩形类,为了对象尽可能小,把点放在一个助的struct 内 #include<iostream> #include<memory> using namespace std; class Point{ public: Point(int x = 0, int y = 0) :m_x(x), m_y(y){} void setX(int newVal){ m_x = newVal; } void setY(int newVal){ m_y = newVal; } private: int m_x; int m_y; }; struct RectData{ Point ulhc; Point lrhc; }; class Rectangle{ //.. public: Rectangle(Point c1, Point c2):pData(new RectData){ pData->ulhc = c1; pData->lrhc = c2; } Point&upperLeft()const{//返回值应加const 以配合常属性函数的本意,也增加了封装性 return pData->ulhc;//返回handles类型时注意对象因离开作用域析构导致的空handles } Point&lowerRight()const{ return pData->lrhc; } private: shared_ptr<RectData>pData; }; #include<iostream> using namespace std; int main(){ Point coord1(0, 0); Point coord2(100, 100); const Rectangle res(coord1, coord2); res.upperLeft().setX(50);//修改了一个常对象 system("pause"); return 0; }
相关文章推荐
- NYOJ 17 单调递增最长子序列 (二分 STL,lower_bound)
- wr703n路由器搭载openwrt系统挂载U盘历程
- 常用正则表达式
- iOS容易造成循环引用的三种场景
- 菜鸟级springmvc+spring+mybatis整合开发用户登录功能(上)
- 文档对象模型DOM(一)
- python文件操作
- CocoaPods安装教程
- 第三方应用使用微博登录授权功能注意事项
- HDU2067 - 小兔的棋盘 (递推)
- Redis各种数据结构介绍以及相应的业务场景应用
- Mysql初始化root密码和允许远程访问
- linux 初级阶段整理笔记
- 深入剖析U3D的Miss Mono Behaviour问题
- HTML 30分钟入门教程
- maven Spring 4.2+SpringMVC+dubbo解决TypeProxyInvocationHandler.invoke(SerializableTypeWrapper.java:239)
- C#23种设计模式
- Kmeans算法寻找合适K值
- hdu2041
- 蚂蚁