Class variables: public access read-only, but private access read/write

后端 未结 12 641
感动是毒
感动是毒 2020-11-28 05:25

Whoopee, not working on that socket library for the moment. I\'m trying to educate myself a little more in C++.

With classes, is there a way to make a variable read-

12条回答
  •  粉色の甜心
    2020-11-28 06:06

    As mentioned in other answers, you can create read only functionality for a class member by making it private and defining a getter function but no setter. But that's a lot of work to do for every class member.

    You can also use macros to generate getter functions automatically:

    #define get_trick(...) get_
    #define readonly(type, name) \
    private: type name; \
    public: type get_trick()name() {\
        return name;\
    }
    

    Then you can make the class this way:

    class myClass {
        readonly(int, x)
    }
    

    which expands to

    class myClass {
        private: int x;
        public: int get_x() {
            return x;
        }
    }
    

提交回复
热议问题