【问题标题】:Ambiguous conversion to reference模糊转换为参考
【发布时间】:2014-09-03 11:38:23
【问题描述】:

为什么这里CL实例到const int&的转换模棱两可?

struct CL
{
    operator const int&()
    {
    }
    operator int&()
    {
    }
};

void fnc(const int&)
{
}

int main()
{
    CL cl;
    fnc(cl);
}

有两种方法:
1)。 cl.operator const int&() 导致用户自定义转换
2)。 cl.operator int&()导致用户自定义转换,然后资格转换(int&到const int&)

第一种方式比第二种方式更好,不是吗?我看到了标准,但什么也没找到。

【问题讨论】:

    标签: c++ operator-overloading ambiguous


    【解决方案1】:

    这是因为在这种情况下,两种转换都适用(同样好)。即int&和const int&都可以被const int&绑定。

    如果你有的话,转换就不会模棱两可了:

    void fnc(int&)
    {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多