I have a class cla and a data member x. I can use cla.x to access its value and cla.x=8 to change its value. However, I want that cla.x only be accessed and can't be assigned. At the same time, I want x can be modified by a class method. Then how to do it? If I set x to be const. It can't be assigned externally. However I can't change it in class either. Code example:

class A{
    int x=9;
    const int y;

A cla=A();
cout<<cla.x<<endl;    //I can access it.
cla.x=7;     //I can modified it.
cout<<cla.y<<endl;    //I can access a const int.
cla.y=8;    //Error.

If I set x to be a private member, I can change it use a class method and let a class method to return its value. But I can't use cla.x to access it.

1 Answers

kilasuelika On

It looks like that I can't do that.

I know that I can use a public method to return private value. But I just don't like the parenthesis of cla.get_x().