calling operators of base class… safe?

后端 未结 3 870
野趣味
野趣味 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<Base&>(*this) = src; // didn't work
            }
    }
    
    0 讨论(0)
  • 2020-12-29 03:12

    This is fine, but it's a lot more readable IMHO to call the base-class by name:

    Base::operator = (rhs);
    
    0 讨论(0)
  • 2020-12-29 03:22

    Yes, it's safe.

    A different syntax to do the same thing could be:

    Base::operator=( rhs );
    
    0 讨论(0)
提交回复
热议问题