why private value of the obj can be changed by class instance?

前端 未结 2 1844
长情又很酷
长情又很酷 2020-12-11 09:58
#include
using namespace std;

class A
{
    private:
        int value;
    public:
        A(int init):value(init){}
        void changevalue(A &am         


        
2条回答
  •  误落风尘
    2020-12-11 10:21

    private doesn't mean "private to the object identity" but "private to the type (and friends)".

    Note that accessibility and being able to write to the type are orthogonal concepts. You can always access a private value inside an object of your own type, but whether you can write to it or not depends on if the object is declared as const:

    void f(A& a){ a.value = 4; } // OK: 'a' is not 'const'
    void g(A const& a){ a.value = 4 } // error: 'a' is marked as ' const'
    

提交回复
热议问题