// Steve J. Hodges, Computer Science, Cabrillo College // CS19 example program, more operator overloading // also demo the "big three" // operator=, copy constructor, destructor recomended // for classes with pointers/new/memory allocation // // PART 1 OF 2 // file: another OOexample1of2.cpp #include class Double{ public: Double(double nd=0.0){ d = nd;} void setValue(double nd){ d = nd;} double getValue()const{ return d;} //equality operator bool operator==(const Double &n){ return ( ( (d+a) >= n.d) && ( (d-a) <= n.d)); } // compound assignment void operator+=(const Double &n){ d += n.d; } // assignment //void operator=(const Double &n); private: double d; static const double a=0.1e-4; }; // assignment overload not really needed // due to "default memberwise copy" being sufficient //void Double::operator=(const Double &n){ // d = n.d; // std::cout << "(in operator=)"; //} // non-member arithmetic operator Double operator+(const Double d1, const Double d2){ Double result; result.setValue(d1.getValue()+d2.getValue()); return result; } // non-member const stream insertion std::ostream &operator<<(std::ostream &os, const Double &obj){ os << obj.getValue(); return os; } // non-member (not const) stream extraction std::istream &operator>>(std::istream &is, Double &obj){ double temp; is >> temp; obj.setValue(temp); return is; } bool operator<(const Double &left, const Double &right){ return (left.getValue() < right.getValue()); } main(){ Double d1, d2(3.4), d3, d4; d1 = d2; d3 = d1 + d2; std::cout << d3 << std::endl; if (d1 < d3){ std::cout << d1 << " is less than " << d3 << std::endl; } std::cout << "d4: Double? "; std::cin >> d4; if (d4 < d3){ std::cout << d4 << " is less than " << d3 << std::endl; } if (d4 == d3){ std::cout << d4 << " is equal to " << d3 << std::endl; } Double d5(d4); d4.setValue(d4.getValue()+1.1); if (d4 == d5){ std::cout << "d4 is surprisingly equal to d5" << std::endl; } }