error C2666: “Date::operator ==”: 重载函数具有类似的转换
2024-01-03 06:12:59
    		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;
}
    			文章来源:https://blog.csdn.net/ArthurHai521/article/details/135352616
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
    	本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!