C++ examples for Class:Operator Overload
Overloaded '+' operator adds two Measures
#include <iostream> using namespace std; class Measure/* w ww .ja va 2 s. c om*/ { private: int feet; float inches; public: Measure() : feet(0), inches(0.0) { } Measure(int ft, float in) : feet(ft), inches(in) { } void getdist() //get length from user { cout << "\nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } void showdist() const { cout << feet << "\'-" << inches << '\"'; } Measure operator + ( Measure ) const; //add 2 distances }; //add this distance to d2 Measure Measure::operator + (Measure d2) const //return sum { int f = feet + d2.feet; float i = inches + d2.inches; if(i >= 12.0) //if total exceeds 12.0, { //then decrease inches i -= 12.0; //by 12.0 and f++; //increase feet by 1 } return Measure(f,i); } int main() { Measure dist1, dist3, dist4; //define distances dist1.getdist(); //get dist1 from user Measure dist2(11, 6.25); //define, initialize dist2 dist3 = dist1 + dist2; //single '+' operator dist4 = dist1 + dist2 + dist3; //multiple '+' operators //display all lengths cout << "dist1 = "; dist1.showdist(); cout << endl; cout << "dist2 = "; dist2.showdist(); cout << endl; cout << "dist3 = "; dist3.showdist(); cout << endl; cout << "dist4 = "; dist4.showdist(); cout << endl; return 0; }