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

后端 未结 12 719
感动是毒
感动是毒 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条回答
  •  旧时难觅i
    2020-11-28 06:08

    While I think a getter function that returns const T& is the better solution, you can have almost precisely the syntax you asked for:

    class myClass {
        private:
        int x_; // Note: different name than public, read-only interface
    
        public:
        void f() {
            x_ = 10; // Note use of private var
        }
        const int& x;
        myClass() : x_(42), x(x_) {} // must have constructor to initialize reference
    };
    
    int main() {
        myClass temp;
    
        // temp.x is const, so ...
        cout << temp.x << endl; // works
        // temp.x = 57;  // fails
    
    }
    

    EDIT: With a proxy class, you can get precisely the syntax you asked for:

    class myClass {
    public:
    
        template 
        class proxy {
            friend class myClass;
        private:
            T data;
            T operator=(const T& arg) { data = arg; return data; }
        public:
            operator const T&() const { return data; }
        };
    
        proxy x;
        // proxy > y;
    
    
        public:
        void f() {
            x = 10; // Note use of private var
        }
    };
    

    temp.x appears to be a read-write int in the class, but a read-only int in main.

提交回复
热议问题