Class Data Encapsulation(private data) in operator overloading

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

    Access specifiers apply at the level of classes, not instances, so the Rational class can see private data members of any other Rational instance. Since your Rational operator+ is a member function, it has access to private data of it's Rational argument.

    Note: the canonical approach is to define a member operator +=, and then use that to implement a non-member operator+

    struct Foo
    {
      int i;
    
      Foo& operator+=(const Foo& rhs) 
      { 
        i += rhs.i;
        return *this;
      }
    
    };
    
    Foo operator+(Foo lhs, const Foo& rhs)
    {
      return lhs += rhs;
    }
    

提交回复
热议问题