Make interfaces easy to use correctly and hard to use incorrectly.
为表现日期的class设计构造函数:
class Date{
public :
Date(int month,int day,int year);
...
};
客户有可能的错误:Date d(30,3,1995);
导入wrapper types:
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 Date{
public:
Date(const Month& m,const Day& d,const Year& y);
...
};
可以这样初始化:
Date d(Month(3),Day(30),Year(1995));
对月份限制其值:
class Month{
public:
static Month Jan(){return Month(1);}
static Month Feb(){return Month(2);}
...
private:
explicit Month(int m);
...
};
Date(Month::Mar(),Day(30),Year(1995));
以函数替换对象,表现某特定月份。