Method chaining + inheritance don't play well together?

后端 未结 15 795
北荒
北荒 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 23:05

    For the second problem, making setAngle virtual should do the trick.

    For the first one, there are no easy solutions. Widget::move returns a Widget, which doesn't have a setText method. You could make a pure virtual setText method, but that'd be a pretty ugly solution. You could overload move() on the button class, but that'd be a pain to maintain. Finally, you could probably do something with templates. Perhaps something like this:

    // Define a move helper function
    template 
    T& move(T& obj, Point& p){ return obj.move(p); };
    
    // And the problematic line in your code would then look like this:
    move(btn, Point(0,0)).setText("Hey");
    

    I'll let you decide which solution is cleanest. But is there any particular reason why you need to be able to chain these methods?

提交回复
热议问题