Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么可以';我不能在比较中使用cast操作符吗?_C++_Typecast Operator - Fatal编程技术网

C++ 为什么可以';我不能在比较中使用cast操作符吗?

C++ 为什么可以';我不能在比较中使用cast操作符吗?,c++,typecast-operator,C++,Typecast Operator,假设以下代码: #include <string> #include <iostream> using namespace std; struct A { operator int() { return 123; } operator string() { return string("abc"); } }; void main() { A a; cout<<(a=

假设以下代码:

#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;
}
#包括
#包括
使用名称空间std;
结构A
{
运算符int()
{
返回123;
}
运算符字符串()
{
返回字符串(“abc”);
}
};
void main()
{
A A;

您是否为类提供了到
int
以及
std::string

这确保了转换的正确进行。
但是,要使
=
工作,所比较的类型必须定义
=


该语言为
int
类型提供了一个隐式
==
,但为
std::string
提供了
=
运算符重载,因此产生了错误。

您是否收到了编译器错误?它说了什么?这告诉了您什么吗?比如,这些参数类型可能没有可用的
=
运算符重载?尝试这样的操作符
const
是正确的,这样您就可以将它们用于
const对象;
。例如
操作符int()const{…}
。因此,简而言之,“int比较是一种语言功能,而字符串比较是一种库功能”@ KrErkSB:简单地说,<代码> STD::String 使用语言规范不要求使用<代码>运算符==/COD>。但是,这可能是库提供的一个特性。- 1这似乎都是错误的。C++标准描述了STD::String。所有的都与<代码>运算符==/COD> >为模板,而不是用户定义的重载与内置的重载。