为什么我不能在比较中使用转换运算符?
Why can't I use the cast operator in comparisions?
假设以下代码:
#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;
}
首先,我将对象a
与int
变量进行比较。然后,我尝试将它与string
变量进行比较,但要编译程序文件。注释掉了包含比较的行,它编译得很好。问题出在哪里?
您为类提供了int
和std::string
的转换运算符,
这样可以确保转换正确进行
但是,要使==
工作,被比较的类型必须定义一个==
该语言为int
类型提供了隐式==
,但为std::string
提供了==
运算符重载,从而导致错误。
相关文章:
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 构造函数和转换运算符之间的重载解析
- 分配给转换运算符失败-C++
- 转换运算符不适用于sleep_until
- 继承模板化转换运算符
- 模板转换运算符在 clang 6 和 clang 7 之间的区别
- 如何在模板化转换运算符中消除此构造的歧义?
- 为什么选择转换运算符的重载?
- 如何避免强制转换运算符 () 和访问运算符 [] 冲突?
- 如果可能的话,C++总是更喜欢右值引用转换运算符而不是常量左值引用吗?
- 了解转换运算符的选择C++
- 多个隐式转换运算符
- 这个typedef和转换运算符语法是什么意思
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 类模板忽略了用户定义的转换运算符(非模板不忽略)
- 为什么在std::for_each()返回时调用转换运算符
- 为什么 std::optional 的强制转换运算符被忽略了
- 使用用户定义的转换运算符推导函数模板参数
- 模板转换运算符的分辨率不明确
- 统一初始化是隐式发生的,即使 int 强制转换运算符是使用 explicit 关键字声明的.原因是什么?