C++之explicit

2850阅读 1评论2013-07-01 scq2099yt
分类:C/C++

        下面举例说明explicit的用处,假设你为一个用来表现日期的class设计构造函数:
        class Date {
        public:
                Date(int month, int day, int year);
                ...
        };
        上面接口咋看挺合适的,但是如果调用者没有注意参数的英文含义或者以错误的次序传递参数就会发生错误:
        Date d(30, 3, 1995);        //误传为日-月-年
        Date d(1995, 3, 30);        //误传为年-月-日
        好吧,大杀器来了:
        //日
        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:    
            Date(const Month& m, const Day& d, const Year& y);
            ...
        };
        Date d(30, 3, 1995);                                    //错误!不正确的类型
        Date d(Day(30), Month(3), Year(1995));        //错误!不正确的类型
        Date d(Month(3), Day(30), Year(1995));        //OK,类型正确
        explicit修饰构造函数表示禁止类型强制转换,这样你就不得不使用合适的类型了




上一篇:C++之赋值操作符operator=
下一篇:C++之强制类型转换

文章评论