作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设您的程序需要跟踪一年中的月份。每个月都有一个名称和以天为单位的长度。显然,这是您要在编译时定义的信息,并且您要限制您的程序,以便在运行时不能定义其他月份信息。当然,您希望无需复杂的方法调用即可方便地访问月份数据。此信息的典型用例大致如下:
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
(我故意使代码尽可能模糊,以表示我不限于任何特定的实现方法。)
解决这个问题最优雅的方法是什么?我正在添加我自己的答案以供公众审查,但欢迎使用其他解决方案。
最佳答案
怎么样:
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++ - 如何限制一个类/结构,使其只能存在某些预定义的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5050261/
有一条(相对)众所周知的 Perl 公理:“只有 Perl 可以解析 Perl”。我想知道 Perl 6 是否仍然如此? 扩大讨论...考虑到 PyPy 最近的更新,我想到了这个问题。 Perl 独特
这是设置。在上一个问题中,我发现我可以通过子组件中的状态传递对象属性,然后使用 componentDidUpdate 获取该对象属性。在这种情况下,状态和属性都称为到达。 这是基本代码... expo
我运行的是 10.5.2 社区版。我已经标记了 源/主要/资源 作为源目录。我可以右键单击并“编译”某些文件,据我所知,这意味着 IDE 将文件复制到与发送类文件的“com.mydomain.pack
我是一名优秀的程序员,十分优秀!