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

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

    The only way I know of granting read-only access to private data members in a c++ class is to have a public function. In your case, it will like:

    int getx() const { return x; }

    or

    int x() const { return x; }.

    By making a data member private you are by default making it invisible (a.k.a no access) to the scope outside of the class. In essence, the members of the class have read/write access to the private data member (assuming you are not specifying it to be const). friends of the class get access to the private data members.

    Refer here and/or any good C++ book on access specifiers.

提交回复
热议问题