C++ 11 智能指针

该代码示例展示了如何在C++中使用智能指针shared_ptr实现工厂模式。Person类作为基类,有Student和Teacher两个子类。PersonInfo结构体存储不同类型人物的信息。CreatePerson函数根据信息创建Person对象,并将其添加到vector容器中。main函数调用CreatePerson,打印出所有人物的信息。
摘要由CSDN通过智能技术生成

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值