c++ proposed exercises (chapter 8: the c++ programing language, fourth edition) - solution -

Post on 16-Dec-2015

38 Views

Category:

Documents

11 Downloads

Preview:

Click to see full reader

DESCRIPTION

.

TRANSCRIPT

  • Chapter 8 Solutions

    1. Before giving the code, it is important to mention that arrays in C++ arent assignable. Thats way I will showtwo equivalent implementations.

    1 # inc lude 2

    3 using std : : cout ;4 using std : : endl ;5

    6 s t r u c t Address {7 const char * name ;8 i n t number ;9 const char * street ;

    10 const char * town ;11 char state [ 2 ] ;12 const char * zip ;13 } ;14

    15 vo id print ( const Address& A ) {16 cout

  • 2. struct with pointer

    1 # inc lude 2

    3 using std : : cout ;4 using std : : endl ;5

    6 s t r u c t Address {7 const char * name ;8 i n t number ;9 const char * street ;

    10 const char * town ;11 char state [ 2 ] ;12 const char * zip ;13 } ;14

    15 vo id print ( const Address& A ) {16 cout

  • 4, 5 Person struct.

    1 # inc lude 2

    3 using std : : cout ; using std : : endl ;4

    5 s t r u c t Person {6 i n t age ;7 char sex ;8 std : : string name , last_name ;9 } ;

    10

    11 vo id print ( const Person& A ) {12 cout

  • 27 }

    main.cpp

    7 Not implemented.

    8 The UML with the constructor is:

    Person

    age: intsex: charname: stringlast name: stringPerson(string,string,int,char):Person

    Figure 1: Person class with constructor

    1 # inc lude 2

    3 using std : : cout ; using std : : endl ;4

    5 s t r u c t Person {6 i n t age_ ;7 char sex_ ;8 std : : string name_ , last_name_ ;9 Person ( const std : : string& name , const std : : string& lastname , const char& sex , const i n t &

    age ) :name_ (name ) ,last_name_ (lastname ) ,sex_ (sex ) ,age_ (age ) { }10

    11 } ;12

    13 vo id print ( const Person& A ) {14 cout

  • 1 # inc lude 2

    3 using std : : cout ;4 using std : : endl ;5

    6 s t r u c t Rectangle {7 const double base ;8 const double height ;9 double area ( ) {

    10 r e t u r n (base * height ) ;11 }12 } ;13

    14 i n t main ( i n t argc , const char * argv [ ] ) {15 Rectangle R={10 ,2 } ;16 cout

  • 12 Person Struct.It would be better to use plain enum rather than enum class due to print function. Change from enum classto enum and identify that no casting is need it.

    1 # inc lude 2

    3 using std : : cerr ;4 using std : : cout ;5 using std : : endl ;6

    7 enum class sex {male = 0 , female = 1 , gay = 2 , lesbian = 3 , transsexual = 4 } ;8 enum class marital_status {single = 0 , married = 1 , divorced = 2 , widow = 3 } ;9

    10 s t r u c t Person {11 std : : string name_ , last_name_ ;12 i n t age_ ;13 sex sex_ ;14 marital_status maritalStatus_ ;15 vo id print ( ) {16 cout

top related