条款18:让接口容易被正确使用,不易被误用

函数接口,class接口,模板template接口,每一种接口都是客户与你的代码互动的手段。

class Data

{

   public:

   Date(int month,int day,int year);

    ....

}

以上代码可能会有两种错误!

1,他们可能传递错误次序参数;

Date d(30, 3, 1995);

2,他们可能传递一个无效的月份或天数;

Date d(2, 30, 1995);

既然这样我们可以导入简单的外覆类型来区别天数,月份,和年份。

struct Day                                          struct Month                                                           struct Year

{                                                                 {                                                                             {

     explicit Day(int d):val(d){}                        explicit Month(int m):val(d) {}                                explict Year(int y):val(y){}

          int val;                                                        int val;                                                                       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));            //ok,类型正确

令Day,Month和Year成为成熟且充分锻炼的类并封装其内数据更好!

class Month

{

  public:

    static Month Jan(){      return Month(1);}

    static Month Feb(){     return Month(2);}

    ....

    static  Month Dec(){  return  Month(12);}

     ...

    private :

    explict Month(int m);

     ...

};

          Date d(Month::Mar(),Day(30),Year(1995));

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值