繁体   English   中英

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

[英]operator= ambiguity in junction with conversion operators

我有以下情况:



    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
    ..\CrossPPTest\TestProxy.cpp(40): could be 'A &A::operator =(const int)'
    ..\CrossPPTest\TestProxy.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&)从- T::T(const U&) ),则不必提供其他分配而不是默认值,并且如果您要隐式地进行异构分配,则必须不提供转换,或者最多不要使它们explicit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM