Method chaining + inheritance don't play well together?

后端 未结 15 768
北荒
北荒 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:58

    Not with C++.

    C++ does not support variance in return types, so there's no way to change the static type of the reference returned from Widget.move() to be more specific than Widget& even if you override it.

    The C++ needs to be able to check things at compile time, so you can't use the fact that what's really being returned from move is a button.

    At best, you can do some runtime casting, but it's not going to look pretty. Just separate calls.

    Edit: Yes, I'm well aware of the fact that the C++ standard says that return value covariance is legitimate. However, at the time I was teaching and practicing C++, some mainstream compilers (e.g., VC++) did not. Hence, for portability we recommended against it. It is possible that current compilers have no issue with that, finally.

提交回复
热议问题