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

前端 未结 19 2211
不知归路
不知归路 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:43

    This answer is an implementation of UncleBens answer

    put in Primitive.hpp

    #pragma once
    
    template
    class Primitive {
    protected:
        T value;
    
    public:
    
        // we must type cast to child to so
        // a += 3 += 5 ... and etc.. work the same way
        // as on primitives
        Child &childRef(){
            return *((Child*)this);
        }
    
        // you can overload to give a default value if you want
        Primitive(){}
        explicit Primitive(T v):value(v){}
    
        T get(){
            return value;
        }
    
        #define OP(op) Child &operator op(Child const &v){\
            value op v.value; \
            return childRef(); \
        }
    
        // all with equals
        OP(+=)
        OP(-=)
        OP(*=)
        OP(/=)
        OP(<<=)
        OP(>>=)
        OP(|=)
        OP(^=)
        OP(&=)
        OP(%=)
    
        #undef OP
    
        #define OP(p) Child operator p(Child const &v){\
            Child other = childRef();\
            other p ## = v;\
            return other;\
        }
    
        OP(+)
        OP(-)
        OP(*)
        OP(/)
        OP(<<)
        OP(>>)
        OP(|)
        OP(^)
        OP(&)
        OP(%)
    
        #undef OP
    
    
        #define OP(p) bool operator p(Child const &v){\
            return value p v.value;\
        }
    
        OP(&&)
        OP(||)
        OP(<)
        OP(<=)
        OP(>)
        OP(>=)
        OP(==)
        OP(!=)
    
        #undef OP
    
        Child operator +(){return Child(value);}
        Child operator -(){return Child(-value);}
        Child &operator ++(){++value; return childRef();}
        Child operator ++(int){
            Child ret(value);
            ++value;
            return childRef();
        }
        Child operator --(int){
            Child ret(value);
            --value;
            return childRef();
        }
    
        bool operator!(){return !value;}
        Child operator~(){return Child(~value);}
    
    };
    

    Example:

    #include "Primitive.hpp"
    #include 
    
    using namespace std;
    class Integer : public Primitive {
    public:
        Integer(){}
        Integer(int a):Primitive(a) {}
    
    };
    int main(){
        Integer a(3);
        Integer b(8);
    
        a += b;
        cout << a.get() << "\n";
        Integer c;
    
        c = a + b;
        cout << c.get() << "\n";
    
        cout << (a > b) << "\n";
        cout << (!b) << " " << (!!b) << "\n";
    
    }
    

提交回复
热议问题