0

我有以下情况:



    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 必须按原样编译。

4

2 回答 2

0

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

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;
}

演示

于 2013-02-11T18:26:28.217 回答
0

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

显然有两种方法可以将 a 分配给Aa B,但没有一种是可取的。

唯一的解决方案(不涉及类)是显式转换,以便您强制必须进行哪种转换。

一般来说,赋值和转换是多余的:如果你承认隐式转换(to - with U::operator T() const- 或 from - with T::T(const U&))你不必提供除默认值之外的赋值,如果你想要隐式异构赋值,你不能提供转换,或最多使它们explicit.

于 2013-02-11T19:55:21.903 回答