我想要一个重载函数,该函数将一个Date对象与另一个Date对象相减,并返回以天为单位的差额。问题是我的重载函数完全看不到所有私有变量。
我试图使其返回Date对象,但没有成功。
这是我的.h文件。
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Date
{
private:
int day;
int month;
int year;
const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public:
Date();
// There are other functions here. That one below is what matters, I guess.
friend int operator - (const Date&, const Date&);
};
下面是我的Date.cpp文件的某些功能。
Date::Date()
{
day = 1;
month = 1;
year = 2000;
}
void Date::setDate()
{
cout << "Month: ";
cin >> month;
while (month < 1 || month > 12)
{
cout << "Invalid month. Try again: ";
cin >> month;
}
cout << "Day: ";
cin >> day;
while (day < 1 || day > monthDays[month - 1])
{
cout << "Invalid day. Try again: ";
cin >> day;
}
cout << "Year: ";
cin >> year;
}
构造函数可以毫无问题地访问monthDays数组。但这不能说关于运算符-:
int operator-(const Date& left, const Date& right)
{
int differenceDays = 0, oprTemp;
// Checks the year.
oprTemp = left.year - right.year;
if (oprTemp >= 0)
differenceDays += oprTemp * 365;
else
return -1;
// Checks the months.
oprTemp = left.month - right.month;
if (oprTemp >= 0)
{
for (int i = 0; i < oprTemp; i++)
differenceDays += monthDays[left.month - 1 - i];
}
else
return -1;
// Checks the day.
oprTemp = left.day - right.day;
if (oprTemp > 0)
differenceDays += oprTemp;
return differenceDays;
}
不要理会上面的功能逻辑。由于明显的原因,它尚未经过测试。 :)
我需要的是一个重载-函数,以返回两个Date对象之间的差额,并以天为单位返回该差额(整数)。如果数据错误,则返回-1。
非常感谢您的耐心和对不起我的英语。 谢谢。
答案 0 :(得分:2)
这是由于monthDays
是Date的非静态成员,因此需要访问对象。
由于operator-(..)是朋友函数,因此没有this
。您可以声明monthDays
静态并使用Date::monthDays
或使用monthDays
或left
的{{1}}成员。由于right
在实例之间不会改变,因此可以与任何对象一起使用。
monthDays
答案 1 :(得分:1)
您应同时将monthDays
值和运算符设为静态,因为它们均不需要引用实例成员。运算符仅通过其参数引用实例成员。操作员必须将数组引用为Date::monthDays
。您也可以将monthDays
声明为constexpr
,因为可以在编译时对其进行评估。
#pragma once
#include <iostream>
#include <string>
class Date {
private:
int day;
int month;
int year;
static constexpr int monthDays[]{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public:
Date();
// There are other functions here. That one below is what matters, I guess.
static friend int operator - (const Date&, const Date&);
};