【发布时间】:2023-03-18 14:43:01
【问题描述】:
我有一个名为Date 的类来控制日期。
我有一个构造函数Date()。如果此构造函数未初始化,则默认日期将由名为 default_ 的私有静态数据成员代替。
我已经在Date.cpp中初始化了default_,如下:
Date Date::default_{1, Month::January, 1900};
其中第一个参数是 int 代表当天,第二个参数是 enum class Month 代表月份,第三个是 int 代表年份。
当我运行这个程序时,我可以打印日期,它会显示由default_ 设置的正确默认日期。
问题:
我希望能够使用函数更改默认日期:
setDefaultDate(int day, Month month, int year)
我该怎么做?我尝试如下实现setDefaultDate(),但它不起作用:
void Date::setDefaultDate(int day, Month month, int year)
{
default_ = {day,month,year};
}
代码:
日期.h:
#ifndef DATE_H
#define DATE_H
// date.h
// class Date declaration
#include <cassert>
#include <iostream>
using namespace std;
enum class Month
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
};
class Date
{
public:
// return the day of the month
int day () const;
// return the month of the year
Month month () const;
// return the year
int year () const;
Date();
static void setDefaultDate(int day, Month month, int year);
private:
int day_;
Month month_;
int year_;
static Date default_;
};
// standalone function for printing the date
void printDate(const Date& date);
#endif
日期.cpp:
// date.cpp
// Implementation of the Date class
#include "date.h"
int Date::day() const
{
return day_;
}
Month Date::month() const
{
return month_;
}
int Date::year() const
{
return year_;
}
// Note, this standalone function is not part of the Date class
void printDate(const Date& date)
{
cout << date.day() << "/"
// cast to an integer to allow the month to be sent to the stream
<< static_cast<int>(date.month()) << "/"
<< date.year()
<< endl;
}
Date Date::default_{1, Month::January, 1900};
void Date::setDefaultDate(int day, Month month, int year)
{
default_ = {day,month,year};
}
Date::Date()
{
day_ = default_.day();
month_ = default_.month();
year_ = default_.year();
}
示例
int main()
{
auto date_1 = Date{};
date_1.setDefaultDate(29, Month::September, 2020);
printDate(date_1);
}
预期输出:
2020 年 9 月 29 日
实际输出:
1900 年 1 月 1 日
它可以编译,但是setDefaultDate() 函数不起作用,并且正在输出default_ 中声明的默认日期。
【问题讨论】:
-
“它不工作:” 是没有问题的描述。请添加更多细节。此外,您的标题有点误导,因为默认构造函数不接受您可以更改的任何参数。
-
你没有三参数构造函数(添加
Date::Date(int day, Month month, int year)) -
“如果此构造函数未初始化,默认日期将由名为 'default_' 的私有静态数据成员放置在其位置” 为什么?只需初始化构造函数中的成员。不需要这个
default_变量。 -
你说的代码为我编译了does not compile,因为缺少默认日期初始化的构造函数。
setDefaultDate还没进图呢。 -
@John 那么请澄清 what 不起作用。最好的方法是minimal reproducible example,它准确地重现您现在遇到的错误。
标签: c++ class constructor static c++17