用c++定义Festival类作为基类,包含属性Name,行为Add,Del,查找指定名字的节日是否存在,定义派生类DateFestival类,新增属性和行为:Date,修改日期.定义派生类WeekDayFestival类,新增属性和行为:节日是几月的第几个星期几,可进行修改
时间: 2023-09-30 17:09:50 浏览: 83
C++类的定义与使用
好的,下面是用C++定义的Festival类作为基类的示例代码:
```cpp
#include <iostream>
#include <string>
class Festival {
protected:
std::string Name;
public:
void Add() {
std::cout << "Festival added." << std::endl;
}
void Del() {
std::cout << "Festival deleted." << std::endl;
}
bool Find(const std::string& name) {
if (Name == name) {
std::cout << "Festival found." << std::endl;
return true;
}
std::cout << "Festival not found." << std::endl;
return false;
}
};
class DateFestival : public Festival {
private:
std::string Date;
public:
void ModifyDate(const std::string& newDate) {
Date = newDate;
std::cout << "Date modified: " << Date << std::endl;
}
};
class WeekDayFestival : public Festival {
private:
std::string WeekDay;
public:
void SetWeekDay(const std::string& weekDay) {
WeekDay = weekDay;
std::cout << "Week day set: " << WeekDay << std::endl;
}
void ModifyWeekDay(const std::string& newWeekDay) {
WeekDay = newWeekDay;
std::cout << "Week day modified: " << WeekDay << std::endl;
}
};
int main() {
// Example usage
DateFestival dateFestival;
dateFestival.Add();
dateFestival.Find("New Year"); // Festival not found.
dateFestival.ModifyDate("January 1st");
WeekDayFestival weekDayFestival;
weekDayFestival.Add();
weekDayFestival.SetWeekDay("Sunday");
weekDayFestival.Find("Christmas"); // Festival not found.
weekDayFestival.ModifyWeekDay("Friday");
return 0;
}
```
这个示例代码定义了一个基类`Festival`,它包含一个属性`Name`和三个行为:`Add()`、`Del()`和`Find()`。然后派生了两个类`DateFestival`和`WeekDayFestival`,分别新增了属性和行为。
`DateFestival`类新增了一个属性`Date`,并添加了一个行为`ModifyDate()`用于修改日期。
`WeekDayFestival`类新增了一个属性`WeekDay`,并添加了两个行为`SetWeekDay()`用于设置星期几,并且`ModifyWeekDay()`用于修改星期几。
在主函数中,我们可以看到对这些类的使用示例。你可以根据需要进行修改和补充。
阅读全文