Skip to content

Commit b23d2f8

Browse files
committed
added drill18 for chapter13
1 parent 9b38b07 commit b23d2f8

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

Chapter13/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,6 @@ Give `Person` a constructor initializing `name` and `age`.
5555

5656
## [Drill 17](drill/17)
5757
Make the representation of `Person` private, and provide `const` member functions `name()` and `age()` to read the name and age.
58+
59+
## [Drill 18](drill/18)
60+
Modify `>>` and `<<` to work with the redefined `Person`.

Chapter13/drill/18/Person.cpp

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

Chapter13/drill/18/Person.h

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

Chapter13/drill/18/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)