// USDollarCast - demonstrate how to write a cast // operator; in this case, the // cast operator converts a USDollar // into a double and the constructor // converts it back #include #include class USDollar { public: // constructor to build a dollar from a double USDollar(double value = 0.0); //the following function acts as a cast operator operator double() { return dollars + cents / 100.0; } // display - simple debug member function void display(char* pszExp, double dV) { cout << pszExp << " = $" << dollars << "." << cents << " (" << dV << ")\n"; } protected: int dollars; int cents; }; // constructor - divide the double value into its // integer and fractional parts USDollar::USDollar(double value) { dollars = (int)value; cents = (int)((value - dollars) * 100 + 0.5); } int main() { USDollar d1(2.0), d2(1.5), d3, d4; //invoke cast operator explicitly... double dVal1 = (double)d1; d1.display("d1", dVal1); double dVal2 = (double)d2; d2.display("d2", dVal2); d3 = USDollar((double)d1 + (double)d2); double dVal3 = (double)d3; d3.display("d3 (sum of d1 and d2 w/ casts)", dVal3); //...or implicitly d4 = d1 + d2; double dVal4 = (double)d3; d4.display("d4 (sum of d1 and d2 w/o casts", dVal4); return 0; }