首页 > 编程语言 > 详细

Effective C++ 条款18

时间:2015-06-25 17:29:20      阅读:247      评论:0      收藏:0      [点我收藏+]

让接口容易被正确使用,不容易被误用

如题目,我们自己的程序接口是面向用户的,程序的目的不但是解决问题,而且要让用户容易使用,所以,必须保证我们的程序接口具有很强的鲁棒性。

怎么保证接口的鲁棒性,不同情况有不同的处理结果,作者列出了以下几个例子所对应的方法。

1.设计一个class来表示日期

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

以上的构造接口很容易被用户用错

Date d(30, 3, 1995);//把月和日弄反了

作者的方法是定义新形式,新类型。

struct Day{
explict 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:
 void Date(const Month& m, const Day& d, const Year& y);
 ……
};

2.第二种情况,为了防止出现下面的赋值把operator*返回const类型。下面的语句就无法通过编译

 if(a*b=c)//这里其实打算做比较,而不是赋值

3.使用智能指针

shared_prt<Investment> createInvestment()
 {
    shared_prt<Investment> retVal(static_cast<Investment*>(0),
                                    getRidOfInvestment);
    retVal=……;//令retVal指向正确对象
    return retVal;
 }

Effective C++ 条款18

原文:http://blog.csdn.net/u011058765/article/details/46637807

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