Skip to content

Commit e9e4e3b

Browse files
committed
added drill16 for chapter13
1 parent f4cd242 commit e9e4e3b

File tree

4 files changed

+43
-0
lines changed

4 files changed

+43
-0
lines changed

Chapter13/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,6 @@ Define a variable of type `Person`, initialize it with "Goofy" and 63, and write
4949

5050
## [Drill 15](drill/15)
5151
Define an input (`>>`) and an output (`<<`) operator for `Person`; read in a `Person` from the keyboard (`cin`) and write it out to the screen (`cout`).
52+
53+
## [Drill 16](drill/16)
54+
Give `Person` a constructor initializing `name` and `age`.

Chapter13/drill/16/Person.cpp

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#include "Person.h"
2+
3+
std::istream& operator>>(std::istream& is, Person& rhs) {
4+
Person p;
5+
if (is >> p.name >> p.age)
6+
rhs = p;
7+
return is;
8+
}
9+
10+
std::ostream& operator<<(std::ostream& os, const Person& rhs) {
11+
return os << rhs.name << ' ' << rhs.age;
12+
}

Chapter13/drill/16/Person.h

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#ifndef PERSON_H
2+
#define PERSON_H
3+
4+
#include <string>
5+
#include <iostream>
6+
7+
struct Person {
8+
Person() {}
9+
Person(const std::string& s, int i)
10+
: name{s}, age{i} {}
11+
std::string name;
12+
int age;
13+
};
14+
15+
std::istream& operator>>(std::istream&, Person&);
16+
std::ostream& operator<<(std::ostream&, const Person&);
17+
18+
#endif

Chapter13/drill/16/main.cpp

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include "Person.h"
2+
3+
#include <iostream>
4+
5+
int main() {
6+
Person p;
7+
std::cout << "Enter person: ";
8+
if (std::cin >> p)
9+
std::cout << p << '\n';
10+
}

0 commit comments

Comments
 (0)