条款18 让接口容易被正确使用,不易被误用
2015-09-05 14:59
246 查看
#include<iostream> #include<memory> using namespace std; class Date{ public: Date(int month, int day, int year){ } }; struct Day{ explicit Day(int d) :val(d){} int val; }; /*struct Month{ explicit Month(int m) :val(m){} int val; };*/ struct Year{ explicit Year(int y) :val(y){} int val; }; /*>>>>>>>>>>>>>>>>>>>>> 防止接口被误用<<<<<<<<<<<<<<<<<<<<<<<*/ class Date1{ public: Date1(const Month&m, const Day&d, const Year&y){ } }; /*>>>>>>>>>>>>>>>>>>>>>限制值<<<<<<<<<<<<<<<<<<<<<<<<*/ class Month{ public: static Month Jan(){return Month(1);} static Month Feb(){ return Month(2); } static Month Mar(){ return Month(3); } private: explicit Month(int m);//阻止生成新的月分 }; /*>>>>>>>>>>>>>>>>>>>>>操持与内置类型一致的行为<<<<<<<<<<<<<<<<<<<<<<<<*/ class Integer{ public: Integer(int i):m_i(i){ } const Integer operator + (const Integer& rhs){ m_i + rhs.m_i; return *this;//返回一个常临时对象 } private: int m_i; }; class Investment{ }; void getRidOfInvestment(){ } /*Investment* */auto_ptr<Investment> createInvestment(){//为达到对象管理资源,把创建资源第一时间存入shared_ptr中 先发制人 //shared_ptr 可以做计数 如果用户试图使用一个错误的资源析构机制getRidOfInvestment函数delete shared_ptr还支持 删除器 可以这样做 shared_ptr<Investment>retVal(static_cast<Investment*>(0), getRidOfInvestment); } int main(){ Date d1(30, 3, 1995);//错误的参数次序 Date d2(30, 2, 1995);//无效的参数 /*---------------------改进后-------------------------------*/ //Date1 d3(30, 3, 1995); 不正确的类型 //Date1 d4(Day(30), Month(3), Year(1995));不正确的类型 //Date1 d5(Month(3), Day(30), Year(1995)); /*>>>>>>>>>>>>>>>>>>>>>限制值<<<<<<<<<<<<<<<<<<<<<<<<*/ Date1 d6(Month::Mar(), Day(30), Year(1995)); /*自定义的types的行为与内置types一致*/ int a, b, c; // a + b = c; system("pause"); return 0; } /* */
相关文章推荐
- Internet采用哪种网络协议?该协议的主要层次结构?
- 左旋转字符串
- Asp.Net上传图片同时生成高清晰缩略图
- ssh密钥认证原理
- 卸载使用“python setup.py install”安装的包
- ssoj1944采矿(oremine)(最长链)
- [LeetCode] Reverse Linked List II(!!!)
- 源泉书签,迁移至阿里云云服务器ECS,带来更好的用户体验
- iOS开发-webView添加头部与尾部控件
- 【leetcode】permutation sequence
- TT 调用动态连接库的函数的方法
- python 递归遍历文件夹
- 时尚地图
- linux free详解
- iOS开发 计算字符串单行的长度
- 九度OJ 题目1152:点菜问题
- Linux命令学习(一)_网络
- 笔试真题解析 TT-2015 春招pc客户端开发练习卷笔试题
- 基于cocos2dx 2.x做的一些shader效果Demo
- 九度OJ 题目1151:位操作练习