Overloading Arithmetic and Assignment Operators for Intuitive Class Behavior - C++ Class

C++ examples for Class:Operator Overload

Description

Overloading Arithmetic and Assignment Operators for Intuitive Class Behavior

Demo Code

#include <iostream>

using namespace std;

class MyClass {/* w  ww .  java  2s.  c  o  m*/
   // These have to see private data
   friend const MyClass operator+(const MyClass& lhs, const MyClass& rhs);
   friend const MyClass operator+(double lhs, const MyClass& rhs);
   friend const MyClass operator+(const MyClass& lhs, double rhs);

public:
   MyClass() : val_(0.0) {}
   MyClass(double val) : val_(val) {}
  ~MyClass() {}

   // Unary operators
   MyClass& operator+=(const MyClass& other) {
      val_ += other.val_;
      return(*this);
   }
   MyClass& operator+=(double other) {
      val_ += other;
      return(*this);
   }

   double getVal() const {return(val_);}

private:
   double val_;
};

// Binary operators
const MyClass operator+(const MyClass& lhs, const MyClass& rhs) {
   MyClass tmp(lhs.val_ + rhs.val_);
   return(tmp);
}

const MyClass operator+(double lhs, const MyClass& rhs) {
   MyClass tmp(lhs + rhs.val_);
   return(tmp);
}

const MyClass operator+(const MyClass& lhs, double rhs) {
   MyClass tmp(lhs.val_ + rhs);
   return(tmp);
}

int main() {

   MyClass checking(500.00), savings(23.91);

   checking += 50;
   MyClass total = checking + savings;

   cout << "Checking balance: " << checking.getVal() << '\n';
   cout << "Total balance: "    << total.getVal() << '\n';
}

Result


Related Tutorials