欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式——原型模式

程序员文章站 2022-06-12 20:18:23
...
#include <iostream>
#include <string>
using namespace std;

class Person
{
public:
    virtual void show() = 0;
    virtual Person* clone() = 0;   // 克隆  复制
};

class Student : public Person
{
public:
    Student(int id = 0, string name = "")
    {
        this->id = id;
        this->name = name;
    }

    Person* clone()
    {
        Student *s = new Student;
        *s = *this;
        return s;
    }
    void show()
    {
        cout <<"id = " << id << ", name = " << name << endl;
    }
private:
    int id;
    string name;
};

void func(Person *p)
{
    // Student s = *p;

    Person *p1 = p->clone();
    p1->show();
}

int main()
{
    Student s1(1, "小明1");
    Student s2 = s1;   // 拷贝构造
    Student s3;
    s3 = s1;   // 赋值运算符

    func(&s1);

    return 0;
}