条款18:让接口容易被正确使用,不易被误用
引入新类型
class Date {
public:
Date(int month, int day, int year);
...
};
Date d(30, 3, 1995); // 错误的参数顺序;
Date d(2, 30, 1995); // 无效的月份或天数;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(30, 3, 1995); // 错误,不正确的类型;
Date d(Day(30), Month(3), Year(1995)); // 错误,不正确的顺序;
Date d(Month(3), Day(30), Year(1995)); // 正确;替客户做那些必要的事情
Last updated