File tree Expand file tree Collapse file tree 4 files changed +49
-0
lines changed
Expand file tree Collapse file tree 4 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -55,3 +55,6 @@ Give `Person` a constructor initializing `name` and `age`.
5555
5656## [ Drill 17] ( drill/17 )
5757Make 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 ` .
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments