【问题标题】:operator= ambiguity in junction with conversion operatorsoperator= 与转换运算符结合的歧义
【发布时间】:2013-02-11 18:21:26
【问题描述】:

我有以下情况:



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

【问题讨论】:

  • @SethCarnegie 我知道显式转换,但谢谢。不能用的原因是第二部分代码会由其他开发者编写,我想让它尽可能简单。
  • 如果您知道显式强制转换并且不想使用它们,那么您为什么不把它放在您的问题中。
  • @SethCarnegie 没有基类...
  • “显式转换”是多余的。这应该是“显式转换”吗?或者也许是“使用演员表”?
  • 你这里的设计很糟糕。

标签: c++ visual-c++ operator-overloading ambiguity


【解决方案1】:

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

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

Demo

【讨论】:

  • 阅读问题的 cmets。不合适。
【解决方案2】:

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

显然有两种方法可以从B 分配给A,但没有一种更可取。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2023-03-28
    相关资源
    最近更新 更多