home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C++ for Dummies (3rd Edition)
/
C_FD.iso
/
CHAP23
/
CHAP23_2.CPP
< prev
Wrap
C/C++ Source or Header
|
1996-09-02
|
2KB
|
78 lines
// Chap23_2.cpp
#include <iostream.h>
#include <iomanip.h>
class Currency
{
public:
Currency(double v = 0.0)
{
unit = v;
cent = int((v - unit) * 100.0 + 0.5);
}
virtual void display(ostream& out) = 0;
protected:
unsigned int unit;
unsigned int cent;
};
class USDollar : public Currency
{
public:
USDollar(double v = 0.0) : Currency(v)
{
}
//display $123.00
virtual void display(ostream& out)
{
out << '$' << unit << '.'
<< setfill('0') << setw(2) << cent
<< setfill(' ');
}
};
class DMark : public Currency
{
public:
DMark(double v = 0.0) : Currency(v)
{
}
//display 123.00DM
virtual void display(ostream& out)
{
out << unit << '.'
//set fill to 0Æs for cents
<< setfill('0') << setw(2) << cent
//now put it back to spaces
<< setfill(' ')
<< " DM";
}
};
ostream& operator<< (ostream& o, Currency& c)
{
c.display(o);
return o;
}
void fn(Currency& c)
{
//the following output is polymorphic because
//operator(ostream&, Currency&) is through a virtual
//member function
cout << "Deposit was " << c
<< "\n";
}
int main()
{
//create a dollar and output it using the
//proper format for a dollar
USDollar usd(1.50);
fn(usd);
//now create a DMark and output it using its own format
DMark d(3.00);
fn(d);
return 0;
}