您的位置:首页 > 其它

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

2015-09-05 14:59 246 查看
#include<iostream>
#include<memory>
using namespace std;
class Date{
public:
Date(int month, int day, int year){

}
};
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 Date1{
public:
Date1(const Month&m, const Day&d, const Year&y){

}
};

/*>>>>>>>>>>>>>>>>>>>>>限制值<<<<<<<<<<<<<<<<<<<<<<<<*/
class Month{
public:
static Month Jan(){return Month(1);}
static Month Feb(){ return Month(2); }
static Month Mar(){ return Month(3); }

private:
explicit Month(int m);//阻止生成新的月分
};
/*>>>>>>>>>>>>>>>>>>>>>操持与内置类型一致的行为<<<<<<<<<<<<<<<<<<<<<<<<*/
class Integer{
public:
Integer(int i):m_i(i){
}
const Integer  operator + (const Integer& rhs){
m_i + rhs.m_i;
return *this;//返回一个常临时对象
}
private:
int m_i;
};
class Investment{

};
void getRidOfInvestment(){

}
/*Investment* */auto_ptr<Investment> createInvestment(){//为达到对象管理资源,把创建资源第一时间存入shared_ptr中 先发制人
//shared_ptr 可以做计数 如果用户试图使用一个错误的资源析构机制getRidOfInvestment函数delete shared_ptr还支持 删除器 可以这样做
shared_ptr<Investment>retVal(static_cast<Investment*>(0), getRidOfInvestment);
}

int main(){
Date d1(30, 3, 1995);//错误的参数次序
Date d2(30, 2, 1995);//无效的参数

/*---------------------改进后-------------------------------*/
//Date1 d3(30, 3, 1995); 不正确的类型
//Date1 d4(Day(30), Month(3), Year(1995));不正确的类型
//Date1 d5(Month(3), Day(30), Year(1995));

/*>>>>>>>>>>>>>>>>>>>>>限制值<<<<<<<<<<<<<<<<<<<<<<<<*/
Date1 d6(Month::Mar(), Day(30), Year(1995));
/*自定义的types的行为与内置types一致*/
int a, b, c;
//	a + b = c;

system("pause");
return 0;
}
/* */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: