键盘上的舞者

My Email: marckywu@gmail.com
随笔 - 19, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

显示构造函数与转换运算符的合作

在设计一个Date类的时候,我们使用int类型来表示年份,如果我们需要对年份进行一些特殊的操作(如:检查,保护等),就很需要定义一个Year类,如下:
class Year {
    
int m_y;
public:
//explicit限制int到Year的隐式转换
    explicit Year(int y)
        : y(m_y) { }
//Year到int的类型转换   
    operator int() const 
        { 
return m_y; }
    
//other funtion
}


class Date {
public :
    Date(
int d, Month m, Year y);
    
//
};

Date d1(
1987, feb, 21);   //error, 21不能隐式转换为Year
Date d2(21, feb, Year(1987)); //ok



在这里Year就只是包裹住了int,对int提供一层保护而已。由于operator int()的存在,只要需要,Year可以隐式的转化为int出现运算表达式中参加运算。而通过给构造函数声明为explicit,就能够保证,int到Year的转化只能在明确无误的情况进行,避免了意外的赋值。

显示构造函数和转换运算符的合作,让Year可以当int使用,同时又对Year进行一定的保护。。。


posted on 2009-08-13 14:39 Marcky 阅读(252) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理