其他分享
首页 > 其他分享> > c – 如何限制类/结构,以便只存在某些预定义的对象?

c – 如何限制类/结构,以便只存在某些预定义的对象?

作者:互联网

假设您的程序需要跟踪一年中的几个月.每个月都有一个名称和天数.显然,这是您希望在编译时定义的信息,并且您希望限制程序,以便在运行时期间不能定义其他月份信息.当然,您希望方便地访问月份数据而无需复杂的方法调用.这些信息的典型用例将大致如下:

Month m = GetRandomMonth();
if ( m == FEBRUARY )
    CreateAppointment(2011, m, 28);

// Iterating over all months would be optional, but a nice bonus
for (/* each month m*/)
    cout << "Month " << m.name << " has " << m.num_days << " days." << endl;

而不应该飞的东西包括:

Month m = Month("Jabruapril", 42);  // should give compiler error

Month m = MonthService().getInstance().getMonthByName("February");  // screw this

(我故意使代码尽可能模糊,以表示我不限于任何特定的实现方法.)

解决这个问题最优雅的方法是什么?我正在添加自己的aswer供公众审查,但欢迎其他解决方案.

解决方法:

怎么样的:

class Month
{
public:
    static const Month JANUARY;
    static const Month FEBRUARY;
    ...

private:
    Month(const std::string &name, int days) : name(name), days(days) {}

    const std::string   name;
    const int           days;
};

const Month Month::JANUARY = Month("January", 31);
const Month Month::FEBRUARY = Month("February", 28);
...

标签:c,class-design
来源: https://codeday.me/bug/20190726/1544026.html