Inherit from const class

后端 未结 8 1602
不思量自难忘°
不思量自难忘° 2021-01-12 00:24

I would like to inherit from a class with the const specifier like this:

class Property
{
    int get() const;
    void set(int a);
};

class Co         


        
8条回答
  •  太阳男子
    2021-01-12 00:52

    If you create a const member function set, you will get what you need.

    class Property
    {
        int get() const;
        void set(int a);
    };
    
    class ConstChild : public Property
    {
        void set(int a) const {}
    };
    

    The only caveat is that a sly user can circumvent your intention by using:

    ConstChild child;
    child.set(10);    // Not OK by the compiler
    
    Property& base = child;
    base.set(10);    // OK by the compiler
    

提交回复
热议问题