加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 操作符==的两个操作数的隐式转换

发布时间:2020-12-16 03:10:25 所属栏目:百科 来源:网络整理
导读:即使没有定义相等的运算符,下面的代码编译并执行没有错误: class A {public: operator bool() const { return true; }};int main(){ A a,b; a == b; //why does this compile? return 0;} 对于一个== b而言内部发生的是对两个操作数都调用了运算符bool()con
即使没有定义相等的运算符,下面的代码编译并执行没有错误:
class A {
public:
    operator bool() const { return true; }
};


int main()
{
    A a,b;
    a == b; //why does this compile?
    return 0;
}

对于一个== b而言内部发生的是对两个操作数都调用了运算符bool()const,然后将两个布尔值进行比较,以相等(这发生在我们的生产代码中,类A是智能指针类型,并在语义上给出可疑的结果).

我的问题是:C标准中的什么规则允许在这种情况下两个操作数的隐式转换?我可以理解,如果另一个操作数已经是一个bool,而不是两个操作数,一个操作数将被隐式转换为bool以进行相等的测试.

解决方法

I can understand that one operand would be implicitly converted …,but not both

然后你被误解了编辑:根据专家的评论,参数依赖查找似乎是一个你的假设是正确的情况.但你的不是ADL的例子.

What rule in the C++ standard allows for the implicit conversion of both operands

从标准草案:

[over.match] (2.9)

  • Then the best viable function is selected based on the implicit conversion sequences (13.3.3.1) needed
    to match each argument to the corresponding parameter of each viable function.

我强调“每个论据”.不是“单一论证”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读