error C2666: “Date::operator ==”: 重载函数具有类似的转换

error C2666: “Date::operator ==”: 重载函数具有类似的转换


1.错误描述

在这里插入图片描述

class Date
{
public:
    Date(int year = 2024, int month = 1, int day = 1)
    {
        _year = year;
        _month = month;
        _day = day;
    }

    bool operator==(const Date& d)
    {
        return _year == d._year
            && _month == d._month
            && _day == d._day;
    }

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

上面的日期类代码编译没问题,但是我在main函数加入测试有问题:

int main()
{
    Date d1;
    Date d2(2024, 1, 2);
    cout << boolalpha << (d1 == d2) << endl;
    return 0;
}

报错如下:

生成开始于 23:46...
1>------ 已启动生成: 项目: BitTest, 配置: Debug x64 ------
1>BitTest.cpp
1>C:\Users\shlyy\Desktop\BitTest\BitTest\BitTest.cpp(33,27): error C2666: “Date::operator ==”: 重载函数具有类似的转换
1>C:\Users\shlyy\Desktop\BitTest\BitTest\BitTest.cpp(16,10):
1>可能是“bool Date::operator ==(const Date &)1>C:\Users\shlyy\Desktop\BitTest\BitTest\BitTest.cpp(16,10):
1>"bool Date::operator ==(const Date &)" [综合表达式 "y == x"]
1>C:\Users\shlyy\Desktop\BitTest\BitTest\BitTest.cpp(33,27):
1>尝试匹配参数列表“(Date, Date)”时
1>已完成生成项目“BitTest.vcxproj”的操作 - 失败。
========== 生成: 0 成功,1 失败,0 最新,0 已跳过 ==========
========== 生成 于 23:46 完成,耗时 00.739 秒 ==========

2.解决方案

在搜索引擎没搜到,然后去ChatGPT上找到了答案:
在这里插入图片描述
修改代码,将重载==的成员函数加上const变成常成员函数:

bool operator==(const Date& d) const
{
    return _year == d._year
        && _month == d._month
        && _day == d._day;
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shlyyy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值