【问题标题】:Assignment operator with derived type argument具有派生类型参数的赋值运算符
【发布时间】:2011-11-13 13:28:11
【问题描述】:
class A {
private:
    A& operator=(const A&);
};

class B : public A {
public:
    B& operator=(const A&) {
            return *this;
    }
};


int main() {

    B b1;
    B b2;

    b1 = b2;

    return 0;
}

这会在编译时出错:

test.cpp: In member function 'B& B::operator=(const B&)':
test.cpp:16:5: error: 'A& A::operator=(const A&)' is private
test.cpp:19:20: error: within this context
test.cpp: In function 'int main()':
test.cpp:31:7: note: synthesized method 'B& B::operator=(const B&)'
first required here 
Build error occurred, build is stopped

由于 B::operator=(A&) 具有非标准签名,编译器生成它自己的 B::operator=(B&),它(尝试)调用 A::operator(A&),它是私有的。

有什么方法可以让编译器也将 B::operator=(A&) 用于 B 参数?

【问题讨论】:

    标签: c++ inheritance operator-overloading


    【解决方案1】:

    我认为尝试对继承类型使用运算符重载是个坏主意。 在 C++ 中,当涉及到运算符重载时,我建议您为每种支持的类型显式提供函数。

    不久前,我自己也陷入了这个陷阱。如果您想了解有经验的 c++ 人如何使用此功能,我建议您查看std::vector<bool> 的模板专业化。

    也许上面的答案可以帮助您解决这个问题: C++ Abstract class operator overloading and interface enforcement question

    另一种可能的解决方案是:

    class B {
    public:
      B& operator=(const A&) {
        return *this;
      }
    };
    
    class A {
    private:
      A& operator=(const A&);
    public:
      operator B() { /* do stuff to convert from A to B */ }
    };
    
    int main() {
    
      B b1;
      B b2;
    
      b1 = b2;
    
      return 0;
    }
    

    【讨论】:

      【解决方案2】:

      这个问题是一个 C++ 问题,我将其与不良概念气味联系起来。

      您的问题很可能是一个错误的问题,而且没有完美的解决方案。想怎么努力就怎么努力,实施的方案总会有问题。

      这是对这个重复问题的(稍微)更完整的答案:How to use base class's constructors and assignment operator in C++?

      顺便说一句,如果赋值运算符是私有的,这清楚地表明基类的作者非常清楚实体语义值语义不会拌匀。相信他,他是对的!

      【讨论】:

      • 我也是基类的作者。我想要做的是拥有一个不可变的基类并在派生类中添加“变异”函数。由于只能读取 operator=() 的 rhs,因此将参数设为对基类的引用是有意义的。
      【解决方案3】:

      当然。只需自己定义运营商并将呼叫转发到operator=(const A&)

      class B : public A {
      public:
          B& operator=(const A&) {
                  return *this;
          }
      
          B& operator=(const B& other) {
              return *this = static_cast<const A&>(other);
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        • 2014-10-19
        • 2020-02-16
        • 2021-07-31
        • 1970-01-01
        相关资源
        最近更新 更多