Define operator +(plus) and cast to double operator : Plus « Overload « C++






Define operator +(plus) and cast to double operator

  
#include <iostream>
using namespace std;
class Power {
   double b;
   int e;
   double val;
 public:
   Power(double base, int exp);
   Power operator+(Power obj) {
      double base;
      int exp; 
      base = b + obj.b;
      exp = e + obj.e;
      Power temp(base, exp);
      return temp;
   }
   operator double(void) {return val;}     
};

Power::Power(double base, int exp){
   b = base;
   e = exp;
   val = 1;
   if (exp!=0)
      while(exp-- > 0)
         val *= b;
}

int main(void){
   Power pwr1(4.0, 2);
   double doub1;

   doub1 = pwr1;                
   cout << (doub1 + 100.2) << endl;

   Power pwr2(3.3, 3), pwr3(0,0);
   pwr3 = pwr1 + pwr2;          
   doub1 = pwr3;                
   cout << doub1;
}
  
    
  








Related examples in the same category

1.Overload the + relative to MyClass.Overload the + relative to MyClass.
2.Overload + for 'ob + int' as well as 'ob + ob'.Overload + for 'ob + int' as well as 'ob + ob'.
3.String class with custom +/- operator
4.additional meanings for the + and = operations
5.overload the "+" operator so that several angles, in the format degrees minutes seconds, can be added directly.
6.Friendly operator+
7.overloaded '+' operator adds two Distances
8.overloaded '+' operator concatenates strings
9.+ is overloaded for three_d + three_d and for three_d + int.
10.Overloading the + (or any other binary operator) using a friend allows a built-in type to occur on the left or right side of the operator.
11.friend overloaded + operator