实例:避免错误参数的方法
来源:互联网 发布:淘宝摄影兼职 编辑:程序博客网 时间:2024/06/02 02:17
class CMonth{public: CMonth(int m = 1): m_month(m) { } private: int m_month; };
上面的例子是一个月份的类,在构造函数调用的时候可能用户会穿入错误的参数,因此为了预防错误的参数可以在构造函数中进行判断但是构造函数没有返回值,一般只能使用std::abort来终止程序,更好的方法是用户不需要传入月份而是使用相应的函数来生成对象来使用,避免错误的发生,如下所示:
class CMonth{ public: static CMonth& Jan() { static CMonth month(1); return month; } static CMonth& Feb() { static CMonth month(2); return month; } static CMonth& Mar() { static CMonth month(3); return month; } static CMonth& Apr() { static CMonth month(4); return month; } static CMonth& May() { static CMonth month(5); return month; } static CMonth& Jun() { static CMonth month(6); return month; } static CMonth& Jul() { static CMonth month(7); return month; } static CMonth& Aug() { static CMonth month(8); return month; } static CMonth& Sep() { static CMonth month(9); return month; } static CMonth& Oct() { static CMonth month(10); return month; } static CMonth& Nov() { static CMonth month(11); return month; } static CMonth& Dec() { static CMonth month(12); return month; } friend std::ostream& operator << (std::ostream &os, const CMonth& m); private: explicit CMonth(int m): m_month(m) { } int m_month; };std::ostream& operator << (std::ostream &os, const CMonth& m){ os << m.m_month << "月" << std::endl; return os;}
1. 需要禁止构造函数的使用
2. 定义静态的函数来生成需要的对象
0 0
- 实例:避免错误参数的方法
- 避免带有变长参数的方法重载
- 避免带有变长参数的方法重载
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例+demo)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- ios--网页js调用oc代码+传递参数+避免中文参数乱码的解决方案(实例)
- django 程序ajax提交的方法,避免csrf错误
- 50个常见的Java错误及避免方法
- JS 时间加减 避免年份错误的方法
- Java可变参数方法的重载实例
- removeChild方法的参数错误解决方案
- 避免竞争条件的实例
- 避免zombie的方法
- 数据持久化
- 1553B命令字与消息传输
- ssi框架学习总结(mvc三层架构)
- JDBC:获取数据库的自动主键
- seo优化
- 实例:避免错误参数的方法
- 【Unity3D游戏开发】NGUI制作字体的三种方法 (二一)
- 网狐“CTableFrameSink”: 不能实例化抽象类
- AndroidL 系统属性的修改
- Jmockit 的使用简单介绍
- 字符串转换成地址
- linux查看在线用户并踢出用户
- python strip()
- 23种设计模式