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

本文探讨了C++中通过自定义类型提高类型安全性的方式,包括使用结构体来表示日期的不同部分,并展示了如何利用智能指针进行资源管理。

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

#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;
}
/* */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值