gpt4 book ai didi

c++ - boolean 运算在 C++ 类内部重载以及类内日期的 if 语句

转载 作者:行者123 更新时间:2023-11-28 02:58:11 25 4
gpt4 key购买 nike

我在上一个问题中使用了这段代码: Adding the year implementation in c++ using a class

我想使用 if 语句来检查日期,如果日期是 31,它会返回到 0 并且月份会递增 1。我什至尝试编写另一个方法并在 + 操作内使用它,但这也失败了,因为我在操作声明内的返回函数中增加了日期。因此,在首先检查条件之前需要增加它!但是如果这个数字最初是 31 呢?没有一个月有 32 天!

我尝试使用它,但由于我的实现,它无法正常工作

我的另一个问题是我也在尝试对操作 == 使用 boolean 引用检查

这是我到目前为止所做的:

bool operator==(const Date&) const;

bool Date::operator==(const Date& date) const
{
if (day == date.day && monthnum == date.monthnum && year == date.year)
return true;
else return false;

}

但出于某种原因,当我尝试通过说例如 date1==date2 来主要测试它时,它无法编译!我写错了吗?

“没有操作==匹配这些操作数”这是我尝试编译代码时遇到的错误

最佳答案

I want to use an if statement to check for dates in a way that if the day was 31 it gets back to 0 and the month gets incremented by one.

这很容易实现:

if (day == 31) {
day = 0;
monthnum++;
}

I try to test it in the main by saying for example, date1==date2, it doesn't compile ! am I writing it wrong ?

是的,您正在声明一个自由函数 operator==,而您想要的是一个成员函数。在 Date 中做:

class Date {
public:
// ...
bool operator==(const Date&) const;
// ...
};

老实说,您也可以使用免费功能,但这需要进行更多更改,而且通常是一样的。以防万一你想使用它,方法如下:

bool operator==(const Date& lhs, const Date& rhs) {
return (lhs.day == rhs.day && lhs.monthnum == rhs.monthnum && lhs.year == rhs.year);
}

(我删除了多余的 if-else 对)。


The compiler states that "no operation == matches these operands". I simply have this code in my main: cout << date1 == date2;

是的,你应该这样做:

cout << (date1 == date2);

否则编译器读取的是:

(cout << date1) == date2;

关于c++ - boolean 运算在 C++ 类内部重载以及类内日期的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21517154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com