n-2*_*2r7 6 c++ oop compare class
我正在为作业编写一个"日期"类,我无法完成其中一项功能.
这是该类的头文件.
class Date
{
public:
Date(); // Constructor without parameters
Date(int m, int d, int y); // Constructor with parameters.
// accessors
int GetMonth(); // returns the size of the diamond
int GetDay();
int GetYear();
// mutators
bool Set(int m, int d, int y);
bool SetFormat(char f);
// standard input and output routines
void Input();
void Show();
void Increment(int numDays = 1);
int Compare(const Date& d);
private:
int month, // month variables
day, // day variable
year; // year variable
char format;
};
Run Code Online (Sandbox Code Playgroud)
我想要的成员函数是int Compare(const Date&d)函数.我需要这个函数来比较两个Date对象(调用对象和参数),并且应该返回:如果调用对象按时间顺序排列,则返回-1;如果对象是相同的日期,则返回0;如果参数对象首先按时间顺序排列,则返回1 .
我试过用==运算符做一个简单的if语句但是我得到了错误.
if (d1 == d2)
cout << "The dates are the same";
return (0);
Run Code Online (Sandbox Code Playgroud)
创建对象后,应该像这样调用函数d1.Compare(d2)
先感谢您!
Ale*_*ler 12
int Date :: Compare (const Date& d) {
if (year<d.year) {
return -1;
}
else if (year>d.year) {
return 1;
}
else if (month<d.month) {
return -1;
}
else if (month>d.month) {
return 1;
}
// same for day
return 0;
}
Run Code Online (Sandbox Code Playgroud)
通常,您还希望提供重载的比较运算符,例如(也在类定义中):
bool operator == (const Date& d) const {
return !Compare(d);
}
bool operator < (const Date& d) const {
return Compare(d)<0;
}
... // consider using boost::operators
Run Code Online (Sandbox Code Playgroud)
PS:有更聪明的实现Compare()- 只需检查其他答案.这个非常简单易读,但完全符合您的规范.
以下是我可以实现比较函数的方法,尽管格式需要一些时间来习惯:
int Date::Compare(const Date& d) const {
return
(year < d.year) ? -1 :
(year > d.year) ? 1 :
(month < d.month) ? -1 :
(month > d.month) ? 1 :
(day < d.day) ? -1 :
(day > d.day) ? 1 :
0;
}
Run Code Online (Sandbox Code Playgroud)
也许:
template<typename T>
int Compare(T a, T b) {
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
int Date::Compare(const Date& d) const {
int a = Compare(year, d.year);
if (a == 0) a = Compare(month, d.month);
if (a == 0) a = Compare(day, d.day);
return a;
}
Run Code Online (Sandbox Code Playgroud)
我不会operator==在比较中使用,虽然operator==如果你想要的话,告诉你如何实现的答案也很好.原因是operator==显然必须查看比较的相同字段,如果它返回false,则Compare将再次执行非常类似的工作.效率可能不是问题,但它重复逻辑.
而对于它的价值,地道的C++是实现operator<可能还有一个一致的operator==和operator>,而不是所有功能于一身的比较功能.运算符是标准算法用于搜索和排序的操作符,其他一切都遵循.Java选择以不同的方式做事.
进入班级的public地区
bool operator==(const Date& rhs) const {
return
year == rhs.year
&& month == rhs.month
&& day == rhs.day
;
}
Run Code Online (Sandbox Code Playgroud)