当初始化需要多个步骤时,初始化变量的正确方法是什么?

时间:2019-05-11 23:12:10

标签: c++ date

我有一个名为Date的类,其中包含日期的月,日,年和工作日。我想在类中包含一个表示当前日期的静态变量,但是初始化它的过程需要多个步骤。我曾考虑过在构造函数中对其进行初始化,但是客户端代码可能希望在构造Date对象之前先对其进行引用。处理此问题的最佳方法是什么?

Date类:

class Date { 
        private: 
                // Date variables 
                unsigned int day; 
                unsigned int month; 
                unsigned int year; 
                unsigned int weekday; 

        public: 
                Date() = default; 
                Date(unsigned int, unsigned int, unsigned int); 

                void add_days(unsigned int);                     

                // Maintain static const info on current date 
                static const Date current_date; 

                // Getter and setter methods 
                unsigned int get_day(); 
                unsigned int get_month(); 
                unsigned int get_year(); 
                unsigned int get_weekday(); 

                void set_day(); 
                void set_month(); 
                void set_year(); 
};

初始化current_date的代码:

time_t raw_time = time(0);
tm current_tm;
localtime_s(&current_tm, &raw_time);
Date temp(current_tm.tm_mon, current_tm.tm_mday, current_tm.tm_year);
temp.weekday = current_tm.tm_wday;
const Date Date::current_date = temp;

谢谢您的任何建议。

0 个答案:

没有答案