Class Data Encapsulation(private data) in operator overloading

前端 未结 5 1304
无人及你
无人及你 2021-01-23 12:19

Below is the code

The Code:

#include 
using namespace std;

class Rational {
  int num;  // numerator
  int den;  // den         


        
5条回答
  •  伪装坚强ぢ
    2021-01-23 12:35

    Why C++ allow the parameter to access private data outside of the class ? Is it some kind of a special case?

    The rule with access specifiers is:
    "Access specifiers apply to per class and not per object"
    So, You can always access private members of a class object in member function of that class.

    A copy constructor/copy assignment operator are commonly used examples of the rule though we do not notice it that often.

    Online Sample:

    class Myclass
    {
        int i;
        public:
           Myclass(){}
           Myclass(Myclass const &obj3)
           { 
                //Note i is private member but still accessible
                this->i = obj3.i;
           }
    };
    
    int main()
    {
        Myclass obj;
        Myclass obj2(obj);
    }
    

    Good Read:
    What are access specifiers? Should I inherit with private, protected or public?

提交回复
热议问题