Inheriting from Transformable and Drawable in SFML

两盒软妹~` 提交于 2019-12-05 06:05:16
Lajos Arpad

If I were you I would define a new class, called TransformableAndDrawable like this:

class TransformableAndDrawable : public sf::Transformable, public sf::Drawable {
    // Your code here
}

In this class you should define all the members which are generally needed by your transformable and drawable classes. Also, in this class you should define all the methods which can be generally implemented in your transformable and drawable classes. Then, your classes should be inherited from TransformableAndDrawable, like this:

class Player : TransformableAndDrawable {
    // Your code here
}

Now, the answer to the first question is: I would implement in the TransformableAndDrawable class the given method if it is a general method, so all the classes inherited from TransformableAndDrawable will have this method.

Instead of giving different names, like p_rect and p_circle, name these members with the same name, like p_shape, so you will have no naming issues. Also, I believe that you can declare your p_shape to be of an ancestor class or interface (I do not know what classes are defined in the library you are working with) and only when needed specify the nature of the shape (whether it is a circle or a rectangle or something else).

As for the second questions: I like the way you have implemented things, but you have made two mistakes:

  • it is not scalable: we want a general solution, a class which can be used for any shape you are working with now and in the future, don't we?
  • it is not general enough: When I want to know the global bounds of a shape, then I am not interested of the nature of the shape, I would prefer your code to handle the nature of the shape without me knowing it

In short, you should do the following:

  1. Create a wrapper class which will be inherited from Transformable and Drawable

  2. In your wrapper class, be agnostic to the nature of the shape, be as general as possible, hopefully there is some class or interface which is ancestor to both RectangleShape and CircleShape.

  3. Inherit all your drawable and transformable classes from your wrapper class, so you will have a shared functionality among your classes

  4. If something in your wrapper class is not good for a class which was inherited from it, overwrite the method in that class.

EDIT:

I have looked into the library you are using in more detail and found out that there is a class called Shape, which is the ancestor to both CircleShape and RectangleShape. So, instead of these classes use Shape and your code will be more general and reusable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!