来自基类和派生类的多态赋值运算符

时间:2018-10-17 15:32:48

标签: c++ polymorphism assignment-operator

我希望能够将派生对象或基础对象复制到派生对象,并且我希望根据复制对象的类型多态选择正确的运算符。

此代码不起作用,我想ChannelOutboundHandlerAdapter使用read(ChannelHandlerContext),因为b1 = (A&)b2;B & operator= (B const &other),但它使用b2

B

我想我必须做点B & operator= (A const &other),但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

我希望能够将派生对象或基础对象复制到派生对象,这是设计不良的症状。

最好争取在类层次结构中仅实例化叶级类的设计。这使您可以拥有整洁的非virtual赋值运算符函数,仅处理正确类型的对象。

class A {
   public:

      // Make A uninstantiable.
      virtual ~A() = 0;

      A & operator= (A const &other) {
         // Here copy A members...
         cout<<"A to A"<<endl;
         return *this;
      }
};

class B: public A {
   public: 

      // Not necessary.
      // B & operator= (A const &other) { ... }

      B & operator= (B const &other) {
         A::operator=(other); // Copy A members.
         // Here copy B members...
         cout<<"B to B"<<endl; 
         return *this;
      }
};
相关问题