运算符=与转换运算符结合时的歧义

operator= ambiguity in junction with conversion operators

本文关键字:运算符 歧义 转换 结合      更新时间:2023-10-16

我有以下情况:


    class B;
    class A {
    private:
        int n;
    public:
        A& operator=(const A& a) {
        }
        A& operator=(const int n) {
            this->n = n;
        }
        friend class B;
    };
    class B {
    private:
        A a;
    public:
        operator A&() {
            return a;
        }
        operator int&() {
            return a.n;
        }
    };

当我执行这个代码时:


    A a;
    B b;
    int i = b;
    a = b;
    a = i;

我有以下错误:


    error C2593: 'operator =' is ambiguous
    ..CrossPPTestTestProxy.cpp(40): could be 'A &A::operator =(const int)'
    ..CrossPPTestTestProxy.cpp(37): or       'A &A::operator =(const A &)'
    while trying to match the argument list '(A, B)'

假设我不能将

A& operator =(const B&)
添加到A类中,如何解决这种歧义。

我必须这样做的原因很复杂,但如果这样的事情能奏效,那就太好了。

可能有一些优先级或类似于明确的运算符关键字的东西。。。如有任何建议,我们将不胜感激。

更新:任何类型的强制转换都不能在代码的第二部分中使用。问题是找到一个只修改第一个代码部分的解决方案。

再更新一次:代码部分#2必须按原样编译。

这看起来像是多态性的作业:

class B;
class A {
   int n;
   public:
      A& operator=(const A& a) {...}
    A& operator=(const int n) {
      this->n = n;
      return *this;
    }
    friend class B;
};
class B : public A {
   A a;
   public:
     operator int&() {
         return a.n;
     }
};
int main() {
    A a;
    B b;
    int i = b; // works
    a = b; // works
    a = i;
}

演示

您提出的方式使问题基本上无法解决。

显然有两种方式可以从B分配给A,但都不是优选的。

唯一的解决方案(不涉及类)是显式强制转换,这样就可以强制进行转换。

通常,赋值和转换是多余的:如果您允许隐式转换(使用U::operator T() const到-或使用T::T(const U&)从-),则不必提供默认值以外的赋值;如果您想要隐式异构赋值,则必须不提供转换,或者最多将其设为explicit