Method chaining + inheritance don't play well together?

后端 未结 15 764
北荒
北荒 2020-12-08 22:20

Consider:

// member data omitted for brevity

// assume that \"setAngle\" needs to be implemented separately
// in Label and Image, and that Button does need         


        
15条回答
  •  再見小時候
    2020-12-08 22:57

    Do setText() and setAngle() really need to return their own types in each class? If you set them all to return Widget&, then you can just use virtual functions as follows:

    struct Widget {
        Widget& move(Point newPos) { pos = newPos; return *this; }
        virtual Widget& setText(string const& newText) = 0;
        virtual Widget& setAngle(double newAngle) = 0;
    };
    
    struct Label : Widget {
        virtual Widget& setText(string const& newText) { text = newText; return *this; }
        virtual Widget& setAngle(double newAngle) { angle = newAngle; return *this; }
    };
    
    struct Button : Label {
        virtual Widget& setAngle(double newAngle) {
            backgroundImage.setAngle(newAngle);
            Label::setAngle(newAngle);
            return *this;
        }
    };
    

    Note that even if the return type is Widget&, the Button- or Label-level functions will still be the ones called.

提交回复
热议问题