This question has already been answered:

I can not figure out with operator overload +. I want to make it possible to add a number to the class object (fraction):

fraction fr(1,5); int x = num; fraction result; result = x + fr; 

Reported as a duplicate by participants αλεχολυτ , Harry , user194374, m9_psy , vp_arth 21 Feb '17 at 15:57 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • need to overload with a separate function; fraction operator+ (int left_op, fraction right_op) { /* ... */ } - mymedia

2 answers 2

Current instance:

 fraction& operator+=(int value) { this->... += value; return *this; } 

New instance:

 fraction operator+(int value) const { return fraction(...); } friend fraction operator+(int value, fraction const& f) { return fraction( value + f./*someoneDataMember*/); /* return ( f + value );*/ } 
  • so the TS has an int variable on the left ... - mymedia
  • @mymedia, updated. - isnullxbh

Like that:

 class fraction{ int value_; public: fraction(int v): value_{v} { } const fraction& operator += (int lhs){ value_ += lhs; return *this; } fraction operator + (int lhs) const{ fraction tmp(value_); tmp += lhs; return tmp; } } 

It may be a little simpler:

 ... fraction operator + (int lhs) const{ return fraction (value_ + lhs); } ... 

This is if the implementation is simple, in general, it is preferable to implement + through + = to eliminate redundant code duplication.

  • Add a little explanation - Volodymyr