设计一个类层次,基类为Date,从Date分别派生出ShortE、MediumDate和LongDate.他们各自有成员函数print(),输出当前日期。 Date输出日期格式为:04-14-2018 ShortE输出日期格式为:14-04-2018 MediumDate输出日期格式为:Apr.14,2018 LongDate输出日期格式为:April 14, 2018
时间: 2023-06-03 15:06:04 浏览: 42
好的,我了解了你的要求。下面是设计的类层次:
```cpp
class Date {
public:
virtual void print() const = 0;
virtual ~Date() {}
};
class ShortE : public Date {
public:
ShortE(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
void print() const override {
std::cout << std::setfill('0') << std::setw(2) << day_ << "-"
<< std::setfill('0') << std::setw(2) << month_ << "-"
<< year_ << std::endl;
}
private:
int year_, month_, day_;
};
class MediumDate : public Date {
public:
MediumDate(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
void print() const override {
std::cout << shortMonth[month_] << "." << day_ << ","
<< year_ << std::endl;
}
private:
int year_, month_, day_;
const std::string shortMonth[13] = {
"N/A", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
};
class LongDate : public Date {
public:
LongDate(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
void print() const override {
std::cout << longMonth[month_] << " " << day_ << ", "
<< year_ << std::endl;
}
private:
int year_, month_, day_;
const std::string longMonth[13] = {
"N/A", "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"
};
};
```
这些类都从基类 `Date` 派生而来,每个类都实现了 `print` 函数,输出对应的日期格式。其中,`ShortE` 采用了最简单的日期格式,每个部分用"-"隔开;`MediumDate` 采用了缩写月份加逗号和年份的格式;`LongDate` 采用完整的月份名和年份的格式。
在实际使用时,我们可以这样创建并输出不同格式的日期:
```cpp
int main() {
Date *date1 = new ShortE(2018, 4, 14);
Date *date2 = new MediumDate(2018, 4, 14);
Date *date3 = new LongDate(2018, 4, 14);
date1->print(); // output: 14-04-2018
date2->print(); // output: Apr.14,2018
date3->print(); // output: April 14, 2018
delete date1;
delete date2;
delete date3;
return 0;
}
```
这里我们首先创建了三个指针,分别指向不同的派生类对象,然后按需调用 `print` 函数输出不同格式的日期。最后别忘了释放内存。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![bat](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)