为什么我不能在比较中使用转换运算符?

Why can't I use the cast operator in comparisions?

本文关键字:转换 运算符 不能 比较 为什么      更新时间:2023-10-16

假设以下代码:

#include <string>
#include <iostream>
using namespace std;
struct A
{
    operator int()
    {
        return 123;
    }
    operator string()
    {
        return string("abc");
    }
};
void main()
{
    A a;
    cout<<(a==123)<<endl;
    //cout<<(a==string("abc"))<<endl;
}

首先,我将对象aint变量进行比较。然后,我尝试将它与string变量进行比较,但要编译程序文件。注释掉了包含比较的行,它编译得很好。问题出在哪里?

您为类提供了intstd::string的转换运算符,
这样可以确保转换正确进行
但是,要使==工作,被比较的类型必须定义一个==
该语言为int类型提供了隐式==,但为std::string提供了==运算符重载,从而导致错误。