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

后端 未结 12 738
感动是毒
感动是毒 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:20

    A simple solution, like Rob, but without contructor:

    class myClass {
        private:
        int m_x=10; // Note: different name than public, read-only interface
        public:
        const int& x=m_x;
    
    };
    
    int main() {
        myClass temp;
    
        // temp.x is const, so ...
        cout << temp.x << endl; // works
        // temp.x = 57;  // fails
    
    }
    

    Is like a get methode, but shorter. Interesant question ... something like. extent const bool member; can save a lot of getters ...but I don't know languages with this feature...

提交回复
热议问题