Make some private members of the const class for some functions

I have a class named myClass:

myClass
{
    int myFunction1();
    int myFunction2();

private:
int A;
int B;
};

In myFunction1A should not change, but B can be changed. The myFunction2B should not be modified, but A can be changed.

Is there a way to make it flexible constfor every function? those. const Bfor function 1 and vice versa.

+4
source share
2 answers

It's impossible. You can declare a method constthat will make all the variables const. You can declare a member mutableso that it can be mutated even in const. However, you cannot declare a member by mutableonly some methods.

: ? A . , .

A B , , :

class MyClass {
private:
   AContainer A;
   BContainer B;
public:
   void myFunction1(){ B.myFynction1(A.get()); }
   void myFunction2(){ A.myFunction2(B.get()); }

   class BContainer {
       int B;
   public:
       int get(){ return B;}
       myFunction1(int A); // May only change B, A is provided as parameter
   }

   class AContainer {
       int A;
   public:
       int get(){ return A;}
       myFunction2(int B); // May only change A, B is provided as parameter
   }

}
+2

, int , , / , ( , - )

class TIntA{
public:
    TIntA(int _i) : m_data(_i) {}

    // this function will be able to modify the m_data member but other
    // functions will have to use the get()
    friend int myClass::myFunction1();

    int get() const {return m_data;}

private:
    int m_data;
};

, ( ? , )

+2

Source: https://habr.com/ru/post/1547582/


All Articles