How to enforce a static member on derived classes?

后端 未结 4 1635
终归单人心
终归单人心 2021-01-12 22:31

I have a base class, Primitive, from which I derive several other classes--Sphere, Plane, etc.

Primitive enforces

4条回答
  •  粉色の甜心
    2021-01-12 23:06

    As all instances of the same class will return the same type, it makes sense to make type() a static method.

    No it does not. You use a static method when you don't need an instance of an object to call the function. In this case you're trying to identify the type of the object, so you do need an instance.

    All method bodies are shared by all objects anyway, so there's no need to worry about duplication. The one exception is when functions are inline, but the compiler will do its best to minimize the overhead and may turn it non-inline if the cost is too great.

    P.S. Requiring a class to identify itself outside of the class hierarchy is usually a bad code smell. Try to find another way.

提交回复
热议问题