calling operators of base class… safe?

后端 未结 3 869
野趣味
野趣味 2020-12-29 02:38

Is following pattern ok/safe ? Or are there any shortcomings ? (I also use it for equality operators)

Derived& operator=(const Derived& rhs)
{
    st         


        
3条回答
  •  囚心锁ツ
    2020-12-29 03:06

    That's better to use

    Base::operator=(rhs);
    

    because if your base class have a pure virtual method the static_cast is not allowed.

    class Base {
        // Attribute
        public:
            virtual void f() = 0;
        protected:
            Base& operator(const Base&);
    }
    
    class Derived {
        public:
            virtual void f() {};
            Derived& operator=(const Derived& src) {
                Base::operator=(src); // work
                static_cast(*this) = src; // didn't work
            }
    }
    

提交回复
热议问题