6.【CPP】Date类的实现

Date.h

#pragma once
using namespace std;
#include<iostream>

class Date
{
	friend ostream& operator<<(ostream& out, const Date& d);
	friend istream& operator>>(istream& in, Date& d);
public:
	//构造函数会被频繁调用,放在类里面作为inline
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	//d1=d3
	Date& operator=(const Date& d)//引用作返回值,不用调用拷贝构造存临时变量
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
		return *this;
	}

	bool operator==(const Date& d)const;
	bool operator!=(const Date& d)const;
	bool operator>(const Date& d)const;
	bool operator>=(const Date& d)const;
	bool operator<(const Date& d)const;
	bool operator<=(const Date& d)const;
	
	//写在类中作为内联
	int GetMonthDay(int year, int month)
	{
		static int days[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
		int day = days[month];
		if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
		{
			day += 1;
		}
		return day;
	}

	Date operator+(int day);
	Date& operator+=(int day);
	Date& operator-=(int day);
	Date operator-(int day);
	Date& operator++(int);
	Date& operator++();
	Date& operator--(int);
	Date& operator--();
	int operator-(const Date& d)const;
	void PrintWeekDay()const;

	void Print()const;

private:
	int _year;
	int _month;
	int _day;
};

inline ostream& operator<<(ostream& out, const Date& d)
{
	out << d._year << "/" << d._month << "/" << d._day;
	return out;
}

inline istream& operator>>(istream& in, Date& d)
{
	in >> d._year >> d._month >> d._day;
	return in;
}

Date.cpp

#include"Date.h"
using namespace std;

//任何一个类,只需要写一个> ==或者< ==重载,剩下的运算符重载复用即可
bool Date::operator==(const Date& d)const
{
	return _year == d._year
		&& _month == d._month
		&& _day == d._day;
}

bool Date::operator!=(const Date& d)const
{
	/*return _year != d._year
		|| _month != d._month
		|| _day != d._day;*/
	return !(*this == d);
}
bool Date::operator>(const Date& d)const
{
	return (_year > d._year)
		|| ((_year == d._year) && (_month > d._month))
		|| (_year == d._year) && (_month == d._month) && (_day > d._day);
}
bool Date::operator>=(const Date& d)const
{
	return (*this > d) || (*this == d);
}
bool Date::operator<(const Date& d)const
{
	return !(*this >= d);
}
bool Date::operator<=(const Date& d)const
{
	return !(*this > d);
}

Date Date::operator+(int day)
{
	Date ret(*this);//拷贝构造
	//Date ret=*this;也是拷贝构造,不是赋值,因为开始变量不存在
	ret += day;

	return ret;
}
Date& Date::operator+=(int day)//支持连续加等,所以有返回值
{
	_day += day;
	while (_day > GetMonthDay(_year, _month))
	{
		_day -= GetMonthDay(_year, _month);
		++_month;
		if (_month==13)
		{
			_year++;
			_month = 1;
		}
	}

	return *this;
}

void Date::Print()const
{
	cout << _year <<"-" << _month<<"-" << _day << endl;
}

Date& Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (_month == 0)
		{
			_year--;
			_month = 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}
Date Date::operator-(int day)
{
	Date ret = (*this);
	ret -= day;

	return ret;
}

Date& Date::operator++(int)
{
	Date ret(*this);
	*this += 1;

	return ret;
}
Date& Date::operator++()
{
	*this += 1;
	return *this;
}

Date& Date::operator--(int)
{
	Date ret(*this);
	*this -= 1;

	return ret;
}
Date& Date::operator--()
{
	*this += 1;
	return *this;
}

int Date::operator-(const Date& d)const//日期减日期
{
	//默认第一个大,第二个小
	Date max = *this;
	Date min = d;
	int flag = 1;

	if (*this < d)
	{
		max = d;
		min = *this;
		flag = -1;
	}

	int count = 0;
	while (min != max)
	{
		min++;
		count++;
	}

	return count * flag;
}

void Date::PrintWeekDay()const
{
	const char* week[] = { "周一","周二","周三","周四","周五","周六","周日" };
	Date start(1900, 1, 1);
	int count = *this-start;
	cout << week[count % 7] << endl;
}

  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
下面是一个使用Qt编写的嵌入式终端应用程序,实现了天气预报模块,并将.h文件和.cpp文件分开。 首先,创建一个名为 "WeatherWidget" 的自定义QWidget,用于实现天气预报模块的界面和逻辑。 **weatherwidget.h**: ```cpp #ifndef WEATHERWIDGET_H #define WEATHERWIDGET_H #include <QWidget> #include <QComboBox> #include <QLabel> #include <QNetworkAccessManager> #include <QNetworkReply> class WeatherWidget : public QWidget { Q_OBJECT public: explicit WeatherWidget(QWidget *parent = nullptr); private: QComboBox *cityComboBox; QComboBox *timeComboBox; QLabel *weatherLabel; QLabel *temperatureLabel; QNetworkAccessManager *networkManager; void setupUI(); void fetchWeatherData(const QString &city, const QString &time); QString parseWeatherData(const QByteArray &data); private slots: void onCityComboBoxIndexChanged(int index); void onTimeComboBoxIndexChanged(int index); void onWeatherDataReceived(QNetworkReply *reply); }; #endif // WEATHERWIDGET_H ``` **weatherwidget.cpp**: ```cpp #include "weatherwidget.h" #include <QVBoxLayout> #include <QJsonObject> #include <QJsonDocument> WeatherWidget::WeatherWidget(QWidget *parent) : QWidget(parent) { setupUI(); networkManager = new QNetworkAccessManager(this); connect(cityComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onCityComboBoxIndexChanged(int))); connect(timeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onTimeComboBoxIndexChanged(int))); connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onWeatherDataReceived(QNetworkReply*))); // 默认显示北京当日天气 fetchWeatherData("北京", "今天"); } void WeatherWidget::setupUI() { QVBoxLayout *layout = new QVBoxLayout(this); cityComboBox = new QComboBox(this); cityComboBox->addItem("北京"); cityComboBox->addItem("上海"); cityComboBox->addItem("广州"); cityComboBox->addItem("深圳"); timeComboBox = new QComboBox(this); timeComboBox->addItem("今天"); timeComboBox->addItem("明天"); timeComboBox->addItem("后天"); weatherLabel = new QLabel(this); temperatureLabel = new QLabel(this); layout->addWidget(cityComboBox); layout->addWidget(timeComboBox); layout->addWidget(weatherLabel); layout->addWidget(temperatureLabel); setLayout(layout); } void WeatherWidget::fetchWeatherData(const QString &city, const QString &time) { QString url = QString("https://api.weatherapi.com/v1/forecast.json?key=YOUR_API_KEY&q=%1&days=3").arg(city); QNetworkRequest request(url); QNetworkReply *reply = networkManager->get(request); reply->setProperty("city", city); reply->setProperty("time", time); } QString WeatherWidget::parseWeatherData(const QByteArray &data) { QString city = ""; QString time = ""; QString weather = ""; QString temperature = ""; QJsonDocument doc = QJsonDocument::fromJson(data); if (!doc.isNull()) { QJsonObject obj = doc.object(); city = obj.value("location").toObject().value("name").toString(); time = obj.value("forecast").toArray()[0].toObject().value("date").toString(); weather = obj.value("forecast").toArray()[0].toObject().value("day").toObject().value("condition").toString(); temperature = obj.value("forecast").toArray()[0].toObject().value("day").toObject().value("avgtemp_c").toString(); } return QString("城市:%1\n时间:%2\n天气:%3\n温度:%4°C").arg(city, time, weather, temperature); } void WeatherWidget::onCityComboBoxIndexChanged(int index) { QString city = cityComboBox->currentText(); QString time = timeComboBox->currentText(); fetchWeatherData(city, time); } void WeatherWidget::onTimeComboBoxIndexChanged(int index) { QString city = cityComboBox->currentText(); QString time = timeComboBox->currentText(); fetchWeatherData(city, time); } void WeatherWidget::onWeatherDataReceived(QNetworkReply *reply) { if (reply->error() == QNetworkReply::NoError) { QByteArray data = reply->readAll(); QString weatherData = parseWeatherData(data); weatherLabel->setText(weatherData); } else { weatherLabel->setText("获取天气数据失败"); } reply->deleteLater(); } ``` 在这个示例中,我们创建了一个WeatherWidget,继承自QWidget。它包含了一个QComboBox用于选择城市和时间,以及两个QLabel用于显示天气和温度。 在setupUI()函数中,我们创建了界面上的控件,并将它们添加到垂直布局中。 fetchWeatherData()函数用于向天气预报API发送网络请求,获取特定城市和时间的天气数据。 parseWeatherData()函数用于解析返回的JSON数据,并提取城市、时间、天气和温度信息。 在槽函数中,我们根据用户选择的城市和时间,调用fetchWeatherData()函数来获取天气数据。当网络请求完成时,通过onWeatherDataReceived()槽函数处理返回的数据,并更新界面上的天气标签。 请注意,示例中的API链接中的"YOUR_API_KEY"需要替换为你自己的API密钥。 希望这个示例能对你有所帮助!如果有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值