What does it mean to be a private member (C ++ classes)?

I am a bit confused about private data elements in C ++ classes. I am new to coding and still in the middle of my “Classes” chapter, so I could get ahead of myself, but I feel that I lack information:

Let's say I have this code:

class clocktype;
{ 
  public:
          void setTime(int,int,int);
          .
          .
          .
   private:
          int hr;
          int min;
          int sec;
     };

And I create a myclock object.

clocktype myclock;
myclock::setTime(hour,minute,min)
{
  if (0<= hour && hour < 24)
  hr = hour;

  if (0<= minute && minute <60)
  min = minute;

  if ( 0<= second && second<60)
  sec = second;
 }
 myclock.setTime(5,24,54);

My textbook says that I cannot do this:

myclock.hr = 5;

because it hris a private member of the data, and the object myclockhas access only to public members. But isn’t that what I generally do in my function setTime? I understand that I am accessing myclock.hrthrough my public member function. But I'm still struggling with the logic of this. What does it mean to be a private member of the data?

+4
4

encapsulation. setter clocktype , , . , , clocktype, . , , setTime, :

class clocktype;
{ 
    public:
        void setTime(int,int,int);
    private:
        int secFromMidnight;
};

clocktype myclock;
myclock::setTime(hour, minute, second)
{
    secFromMinight = second + (minute * 60) + (hour * 24 * 60);
}
+2

setTime , .

, , , - , .

+1

++ , , - ( ). [ ] setTime , , .

class clocktype;
{ 
 private:
          int hr;
          int min;
          int sec;

  public:
          void setTime(int hour,int minute,int min)
 {
  if (0<= hour && hour < 24)
  hr = hour;

  if (0<= minute && minute <60)
  min = minute;

  if ( 0<= second && second<60)
  sec = second;
  }
 };

( ) setTime, .

+1

(/) :

  • , , , .
  • , , , ( ).

, , - setTime(), . , , . , , , , , , is . , , , , . setTime().

So basically, it's just something internal to programmers who share libraries. This is just a clean way to write code. In the end, for the final result, when the program is running, it does not matter if everything is open. In other words: this is a programming game, and we play by the rules we create to guarantee clean code and long-term stability.

+1
source

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


All Articles