shared_prt使用
Person.h
#include <string>
#include <iostream>
using namespace std;
class Person
{
private:
string m_name;
uint8_t m_age;
protected:
string m_info;
public:
Person(string name, uint8_t age);
void Setinfo(string info)
{
m_info = info;
}
virtual void PrintInfo() = 0;
~Person();
};
Person::Person(string name, uint8_t age)
:m_name(name), m_age(age)
{
}
Person::~Person()
{
}
class Student:public Person
{
public:
Student(string name, uint8_t age)
:Person(name ,age){
}
void PrintInfo(){
cout << "i am a student " << m_info << endl;
}
~Student(){};
};
class Teacher:public Person
{
public:
Teacher(string name, uint8_t age)
:Person(name ,age){
}
void PrintInfo(){
cout << "i am a teacher " << m_info << endl;
}
~Teacher(){};
};
factory.h
#include<map>
#include<vector>
#include <string>
#include<memory>
#include "Person.h"
using namespace std;
struct PersonInfo
{
string type;
string name;
uint8_t age;
string info;
};
vector<shared_ptr<Person>> vPerson;
vector<PersonInfo> vInfo = {
PersonInfo{"student","judy",20,"我住在昌平"},
PersonInfo{"teacher","alex",30,"不要挑战我"},
PersonInfo{"student","andy",18,"我是留学生"},
PersonInfo{"teacher","jinchao",35,"我教编程技术"}
};
void CreatePerson()
{
for (auto ps : vInfo)
{
if (ps.type.find("teacher") != string::npos)
{
auto tc = make_shared<Teacher>(Teacher(ps.name, ps.age));
tc->Setinfo(ps.info);
vPerson.push_back(tc);
}
else if (ps.type.find("student") != string::npos)
{
auto st = make_shared<Student>(ps.name, ps.age);
st->Setinfo(ps.info);
vPerson.push_back(st);
}
else{
cout << ps.type << "is invalid";
}
}
for (auto ps : vPerson)
{
ps->PrintInfo();
}
}
shared_ptr.cpp
#include <memory>
#include "factory.h"
int main()
{
CreatePerson();
return 0;
}