Class Data Encapsulation(private data) in operator overloading

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

    Rational::operator+ is a member function, so it has access to all members of every Rational object.

    Coding tip: this kind of things is usually written in two parts: an operator+= that's a member, and an operator+ that's not. Like this:

    Rational& Rational::operator+=(const Rational& rhs) {
        num = num * rhs.den + den * rhs.num;
        den *= rhs.den;
        return *this;
    }
    
    Rational operator+(const Rational& lhs, const Rational& rhs) {
        Rational result(lhs);
        result += rhs;
        return result;
    }
    

提交回复
热议问题