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> >为模板,而不是用户定义的重载与内置的重载。