1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
#include <iostream>
#include <string>
struct person
{
virtual ~person() = default ;
person( std::string name = {}, int age = 0, std::string ssn = {} )
: m_name(name), m_age(age), m_ssn(ssn) { /* if( age < 0 ) etc. */ }
std::string name() const { return m_name ; }
void rename( std::string name ) { m_name = name ; }
int age() const { return m_age ; }
void age( int new_age ) { /* if( age < 0 ) etc. */ m_age = new_age ; }
std::string ssn() const { return m_ssn ; }
void ssn( std::string new_ssn ) { m_ssn = new_ssn ; }
// etc.
virtual std::ostream& write( std::ostream& stm ) const
{ return stm << "name: " << name() << " age: " << age() << " yrs ssn: " << ssn() ; }
virtual std::istream& read( std::istream& stm ) { /* TODO */ return stm ; }
private:
std::string m_name;
int m_age;
std::string m_ssn;
};
std::ostream& operator<< ( std::ostream& stm, const person& p ) { return p.write(stm) ; }
std::istream& operator>> ( std::istream& stm, person& p ) { return p.read(stm) ; }
struct student : person
{
student( std::string name = {}, int age = 0, std::string ssn = {}, double gpa = 0 )
: person( name, age, ssn ), m_gpa(gpa) { /* if( gpa < 0 ) etc. */ }
double gpa() const { return m_gpa ; }
void gpa( double new_gpa ) { /* validate gpa */ m_gpa = new_gpa ; }
virtual std::ostream& write( std::ostream& stm ) const override
{ return person::write(stm) << " gpa: " << gpa() ; }
virtual std::istream& read( std::istream& stm ) override { /* TODO */ return stm ; }
private: double m_gpa ;
};
int main()
{
person p { "capablanca", 127, "12345" } ;
student s { "grunfeld", 122, "56789", 9.4 } ;
std::cout << p << '\n' << s << '\n' ;
}
| |