我有一个 Date 类,我试图用一个简单的程序进行测试,要求用户以某种格式输入日期,然后将其放入类中。这个想法是允许用户从任何以正确格式开始的文本字符串设置 Date 类。
这是我的日期类头文件(其他功能的暗示与这篇文章无关):
#ifndef DATE_HPP_
#define DATE_HPP_
#include <iostream>
#include <cstdio>
class Date {
public:
int Year;
int Month;
int Day;
int HH;
int MM;
int ss;
Date();
int getTotalSeconds();
/*
* Overloaded Operator Functions
*/
//Assignments
Date operator=(Date input);
//Comparisons
bool operator==(Date& rhs);
bool operator!=(Date& rhs);
bool operator<(Date& rhs);
bool operator>(Date& rhs);
bool operator<=(Date& rhs);
bool operator>=(Date& rhs);
//Conversion
operator char*();
operator std::string();
//Declared as member functions
std::ostream& operator<<(std::ostream& os){
os << "operator<<: " << this->Year << '-' << this->Month << '-' << this->Day << '-' << this->HH << ':' << this->MM << ':' << this->ss;
return os;
}
std::istream& operator>>(std::istream& is){
char input[20];
is >> input;
scanf(input,"%04d-%02d-%02d-%02d:%02d:%02d",Year,Month,Day,HH,MM,ss);
is.clear();
return is;
}
};
#endif
我的测试程序如下所示:
#include <iostream>
#include "Date.hpp"
int main(int argc, char* argv[]){
Date date;
std::cout << "Date initialized, printing: \n" << date << std::endl;
std::cout << "This is a test of the date library!\nPlease enter a date in the form YYYY-MM-DD-HH:mm:ss: ";
std::cin >> date;
std::cout << "\n\nDate reset, printing:\n" << date << std::endl << "Exit!\n";
return 0;
}
我不知道我做错了什么。我一直在查找有关重载运算符的信息,并且 operator<< 效果很好!(在尝试重载运算符之前,我编译并测试了所有内容>>)如果有帮助,我在 Arch linux 上使用 gcc。