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

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

    There is a way to do it with a member variable, but it is probably not the advisable way of doing it.

    Have a private member that is writable, and a const reference public member variable that aliases a member of its own class.

    class Foo
    {
      private:
          Bar private_bar;
    
      public:
          const Bar& readonly_bar; // must appear after private_bar
                                  // in the class definition
    
      Foo() :
           readonly_bar( private_bar )
      {
      }
    };
    

    That will give you what you want.

    void Foo::someNonConstmethod()
    {
        private_bar.modifyTo( value );
    }
    
    void freeMethod()
    {
        readonly_bar.getSomeAttribute();
    }
    

    What you can do, and what you should do are different matters. I'm not sure the method I just outlined is popular and would pass many code reviews. It also unnecessarily increases sizeof(Foo) (albeit by a small amount) whereas a simple accessor "getter" would not, and can be inlined, so it won't generate more code either.

提交回复
热议问题