Why can't I inherit from int in C++?

前端 未结 19 2323
不知归路
不知归路 2020-12-02 18:24

I\'d love to be able to do this:

class myInt : public int
{

};

Why can\'t I?

Why would I want to? Stronger typing. For example, I

19条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 18:35

    strong typing of ints (and floats etc) in c++

    Scott Meyer (Effective c++ has a very effective and powerful solution to your problem of doing strong typing of base types in c++, and it works like this:

    Strong typing is a problem that can be addressed and evaluated at compile time, which means you can use the ordinals (weak typing) for multiple types at run-time in deployed apps, and use a special compile phase to iron out inappropriate combinations of types at compile time.

    #ifdef STRONG_TYPE_COMPILE
    typedef time Time
    typedef distance Distance
    typedef velocity Velocity
    #else
    typedef time float
    typedef distance float
    typedef velocity float
    #endif
    

    You then define your Time, Mass, Distance to be classes with all (and only) the appropriate operators overloaded to the appropriate operations. In pseudo-code:

    class Time {
      public: 
      float value;
      Time operator +(Time b) {self.value + b.value;}
      Time operator -(Time b) {self.value - b.value;}
      // don't define Time*Time, Time/Time etc.
      Time operator *(float b) {self.value * b;}
      Time operator /(float b) {self.value / b;}
    }
    
    class Distance {
      public:
      float value;
      Distance operator +(Distance b) {self.value + b.value;}
      // also -, but not * or /
      Velocity operator /(Time b) {Velocity( self.value / b.value )}
    }
    
    class Velocity {
      public:
      float value;
      // appropriate operators
      Velocity(float a) : value(a) {}
    }
    

    Once this is done, your compiler will tell you any places you have violated the rules encoded in the above classes.

    I'll let you work out the rest of the details yourself, or buy the book.

提交回复
热议问题