Category : C++ Source Code
Archive   : TEACHCPP.ZIP
Filename : EX07009.CPP

 
Output of file : EX07009.CPP contained in archive : TEACHCPP.ZIP

// ex07009.cpp
// Contexts for conversions
#include

// -------- Julian date class
class Julian {
public:
int da, yr;
Julian() {}
Julian(int d, int y) { da = d; yr = y;}
void display(){cout << '\n' << yr << '-' << da;}
};

// ------- date class
class Date {
int mo, da, yr;
public:
Date(int m, int d, int y) { mo = m; da = d; yr = y; }
operator Julian(); // conversion function
};

// ----- a class that expects a Julian date as an initializer
class Tester {
Julian jd;
public:
Tester(Julian j) { jd = j; }
void display() { jd.display(); }
};

static int dys[] = {31,28,31,30,31,30,31,31,30,31,30,31};

// ---- member conversion function (Julian <- Date)
Date::operator Julian()
{
Julian jd(0, yr);
for (int i = 0; i < mo-1; i++)
jd.da += dys[i];
jd.da += da;
return jd;
}

// -------- a function that expects a Julian date
void dispdate(Julian jd)
{
jd.display();
}

// --------- a function that returns a Julian Date
Julian rtndate()
{
Date dt(10,11,88);
return dt; // this will be converted to Julian
}

main()
{
Date dt(11,17,89);
Julian jd;
// ------- convert Date to Julian via assignment
jd = dt;
jd.display();
// ------- convert Date to Julian via function argument
dispdate(dt);
// ------- convert Date to Julian via initializer
Tester ts(dt);
ts.display();
// ------- convert Date to Julian via return value
jd = rtndate();
jd.display();
}