原型模式
要点:clone一个对象 拷贝构造函数必须重写
#define _CRT_SECURE_NO_WARNINGS//这里编译没通过,所以去属性里面改吧 先换成strcpy_s用
#include <iostream>
using namespace std;
class Student
{
public:
Student(){}
Student(const Student&) {};
~Student() {
printf("Destruct Student\n");
}
virtual void getStudentInfo() = 0;
virtual Student *clone() = 0;
protected:
char name[20];
int id;
};
class StudentType : public Student
{
public:
StudentType(const char* input_name){//this "const" must be exist, or it would be compile error
strcpy_s(name, input_name);//无法从“const char [9]”转换为“char *”
this->id = 0;
printf("StudentType Construct\n");
}
StudentType() {}
StudentType(const StudentType& stuType) {
printf("copy Construct StudentType\n");
this->id = stuType.id;
this->id++;
strcpy_s(name, stuType.name);
}
StudentType* clone() override {
return new StudentType(*this);
}
virtual void getStudentInfo() override {
printf("student name is %s, id is %d\n", name, id);
}
~StudentType() {
printf("Destruct StudentType\n");
}
};
int main(){
const char* str = "xiaoming";
Student *stu = new StudentType(str);
Student *stu1 = stu->clone();
Student *stu2 = stu1->clone();
stu->getStudentInfo();
stu1->getStudentInfo();
stu2->getStudentInfo();
delete stu2;
delete stu1;
delete stu;
cout << "hello" << endl;
return 0;
}
结果
StudentType Construct
copy Construct StudentType
copy Construct StudentType
student name is xiaoming, id is 0
student name is xiaoming, id is 1
student name is xiaoming, id is 2
Destruct Student
Destruct Student
Destruct Student
hello