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

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

    What others have said is true... int is a primitive in C++ (much like C#). However, you can achieve what you wanted by just building a class around int:

    class MyInt
    {
    private:
       int mInt;
    
    public:
       explicit MyInt(int in) { mInt = in; }
       // Getters/setters etc
    };
    

    You can then inherit from that all you jolly want.

提交回复
热议问题