Class Data Encapsulation(private data) in operator overloading

前端 未结 5 1316
无人及你
无人及你 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:24

    The question reveals a misunderstanding: "Why C++ allow the parameter to access private data outside of the class ?"

    The method operator+ does belong to the class: it is declared within the class and in its implementation you'll see that the method is a member of the class by the prefix class_name:: So with operator+ there is no access if private members outside of the class.

    The operators << and >> are a different case - these really do not belong to the class, since they are called by a stream object. That's why their implementation doesn't have the prefix Rational::. To allow these operators the access to private data of the object they are declared to be friends of the class within the class declaration. By declaring functions or classes to be friend of my own class I show that I trust them not to tamper with the private data of my class.

提交回复
热议问题