实例:避免错误参数的方法

来源:互联网 发布:淘宝摄影兼职 编辑:程序博客网 时间:2024/06/02 02:17
class CMonth{public:        CMonth(int m = 1): m_month(m)    {            }    private:        int m_month;    };


上面的例子是一个月份的类,在构造函数调用的时候可能用户会穿入错误的参数,因此为了预防错误的参数可以在构造函数中进行判断但是构造函数没有返回值,一般只能使用std::abort来终止程序,更好的方法是用户不需要传入月份而是使用相应的函数来生成对象来使用,避免错误的发生,如下所示:

class CMonth{    public:        static CMonth& Jan()    {        static CMonth month(1);        return month;    }        static CMonth& Feb()    {        static CMonth month(2);        return month;    }        static CMonth& Mar()    {        static CMonth month(3);        return month;    }        static CMonth& Apr()    {        static CMonth month(4);        return month;    }        static CMonth& May()    {        static CMonth month(5);        return month;    }        static CMonth& Jun()    {        static CMonth month(6);        return month;    }        static CMonth& Jul()    {        static CMonth month(7);        return month;    }        static CMonth& Aug()    {        static CMonth month(8);        return month;    }        static CMonth& Sep()    {        static CMonth month(9);        return month;    }        static CMonth& Oct()    {        static CMonth month(10);        return month;    }        static CMonth& Nov()    {        static CMonth month(11);        return month;    }        static CMonth& Dec()    {        static CMonth month(12);        return month;    }        friend std::ostream& operator << (std::ostream &os, const CMonth& m);    private:        explicit CMonth(int m): m_month(m)    {            }        int m_month;    };std::ostream& operator << (std::ostream &os, const CMonth& m){    os << m.m_month << "月" << std::endl;    return os;}

1. 需要禁止构造函数的使用

2. 定义静态的函数来生成需要的对象


0 0
原创粉丝点击