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

本文介绍如何通过使用Wrapper Types来改进日期类的设计,使之更易于正确使用且难以误用。通过具体示例展示了如何定义Month、Day及Year结构体,并通过限制月份的有效值进一步提高安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Make interfaces easy to use correctly and hard to use incorrectly.

为表现日期的class设计构造函数:

class Date{

public :

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

...

};

 

客户有可能的错误:Date d(30,3,1995);

 

导入wrapper types:

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(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(Month::Mar(),Day(30),Year(1995));

以函数替换对象,表现某特定月份。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值