Compare commits
2
Commits
058179b643
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5993dd1dc8 | ||
|
|
4e2e5f72a2 |
@@ -1,10 +1,17 @@
|
||||
#include "Person.h"
|
||||
#include "PersonException.h"
|
||||
#include "YoungPerson.h"
|
||||
#include <cstddef>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
using std::cout;
|
||||
|
||||
std::shared_ptr<Person> Person::GetPerson(std::string name, int age) {
|
||||
if (age < 18) return std::make_shared<YoungPerson>(name, age);
|
||||
return std::make_shared<Person>(name, age);
|
||||
}
|
||||
|
||||
Person::Person(std::string name, int age) : name(name), age(age) {
|
||||
if (age < 0) {
|
||||
throw PersonException("negative age");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#ifndef Person_h
|
||||
#define Person_h
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
class Person {
|
||||
@@ -15,6 +16,8 @@ class Person {
|
||||
|
||||
void setSalary(int sal);
|
||||
|
||||
static std::shared_ptr<Person> GetPerson(std::string name, int age);
|
||||
|
||||
private:
|
||||
Person(const Person &);
|
||||
|
||||
|
||||
+3
-9
@@ -1,5 +1,6 @@
|
||||
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -14,7 +15,7 @@ using std::string;
|
||||
using std::exception;
|
||||
|
||||
int main() {
|
||||
std::vector<Person *> people;
|
||||
std::vector<std::shared_ptr<Person>> people;
|
||||
|
||||
string namePrompt = "Enter name: ";
|
||||
string name;
|
||||
@@ -38,7 +39,7 @@ int main() {
|
||||
throw PersonException("invalid age");
|
||||
}
|
||||
|
||||
Person *personPtr = new Person(name, age);
|
||||
auto personPtr = Person::GetPerson(name, age);
|
||||
|
||||
cout << salaryPrompt;
|
||||
cin >> salary;
|
||||
@@ -64,12 +65,5 @@ int main() {
|
||||
cin >> name;
|
||||
}
|
||||
|
||||
// delete all the person(s) in the vector
|
||||
for (std::vector<Person *>::iterator iter = people.begin(); iter != people.end(); ++iter) {
|
||||
delete *iter;
|
||||
}
|
||||
|
||||
cout << "There are " << Person::GetCount() << " Person(s) left dangling\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user