首页 > 编程语言 > 详细

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

时间:2018-06-23 17:51:06      阅读:189      评论:0      收藏:0      [点我收藏+]

记住:

  • 好的接口容易被正确使用,不容易被误用。你应该在你的所有接口中努力达成这些性质。
  • 促进正确使用的办法包括接口的一致性,以及与内置类型的行为兼容。
  • 阻止误用的办法包括建立新类型,限制类型上的操作,束缚对象值,以及消除客户的资源管理责任。
  • tr1::shared_ptr支持定制型删除器。这可被用来自动解除互斥锁等等。

 

class Data {
public:
    Date(int month, int day, int year);
};

Date d(30, 3, 1995); //错误,应该是3,30

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)); //正确

 

class Month {
public:
    static Month Jan() { return Month(1); }
    static Month Feb() { return Month(2); }
    ...
private:
    explicit Month(int m);
};

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

 

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

原文:https://www.cnblogs.com/pfsi/p/9218061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!