使变量只读,但C++中的客户端仍然可以访问它?

Mic*_*gar 2 c++

有没有办法做到这一点:

class example {
public:
   const int dontModifyMe;

   example() {
      // setup for dontModifyMe..
      dontModifyMe = getValueForDontModifyMe(earlierSetup);
   }
}

example ex;
cout << ex.dontModifyMe; // works
ex.dontModifyMe = 4 // error
Run Code Online (Sandbox Code Playgroud)

如果dontModifyMe不需要设置,我只会使用成员初始化列表.有没有办法解决这个问题,不需要显式的getter/setter方法?

Chr*_*itt 9

我过去使用过的东西是:

class example {
    int m_theValue;
public:
    const int &theValue = m_theValue; 
}
Run Code Online (Sandbox Code Playgroud)

这允许您通过m_theValue在内部编辑值,同时在"公共"域中保持常量接口可用.它类似于getter/setter方法,但不需要实际使用所述方法.