C++模板方法模式
模板方法模式:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。
主要实现就是通过继承、纯虚函数,需要理解的地方主要是有纯虚函数的类,派生类的内存存储。
#include "stdafx.h" #include <process.h> #include <iostream> using namespace std; //试卷模板 class TestPaper { public: void TestQuestion1() { cout<<"杨过得到玄铁,后来给了郭,炼成倚天剑,请问玄铁可能为() a 球磨矿, b 马口铁 c 高速合金钢, d 碳素纤维"<<endl; cout<<endl; cout<<"答案是:"<<answer1()<<endl; cout<<endl; } void TestQuestion2() { cout<<"杨过,程英,陆无双铲除了情花,造成了,() a 这种植物不再害人, b 使一种珍惜植物灭绝 c 破坏了生态平衡, d 造成该地区沙漠化"<<endl; cout<<endl; cout<<"答案是:"<<answer2()<<endl; cout<<endl; } void TestQuestion3() { cout<<"蓝凤凰致使华山师徒,桃谷六仙呕吐不止,如果你是医生,请问你要用什么药() a 阿斯匹林, b 牛黄解毒片 c 氲气, d 牛奶"<<endl; cout<<endl; cout<<"答案是:"<<answer3()<<endl; cout<<endl; } virtual ~TestPaper() { } TestPaper() { } public: virtual char answer1()=0; virtual char answer2()=0; virtual char answer3()=0; }; //学生A的试卷 class TestPaperA:public TestPaper { public: TestPaperA() { } ~TestPaperA() { } public: char answer1(){return 'C';} char answer2(){return 'C';} char answer3(){return 'C';} }; //学生B的试卷 class TestPaperB:public TestPaper { public: TestPaperB() { } ~TestPaperB() { } public: char answer1() { return 'A'; } char answer2() { return 'B'; } char answer3() { return 'A'; } }; int main() { cout<<"-------------------学生A的试卷-------------------"<<endl<<endl; TestPaper *pStuA=new TestPaperA(); pStuA->TestQuestion1(); pStuA->TestQuestion2(); pStuA->TestQuestion3(); cout<<endl<<endl; cout<<"------------------学生B的试卷------------------"<<endl<<endl; TestPaper *pStuB=new TestPaperB(); pStuB->TestQuestion1(); pStuB->TestQuestion2(); pStuB->TestQuestion3(); system("pause"); return 0; }
- 一个包含虚函数的类,将定义一个虚函数列表,称为vtbl。此列表的每一个slot都指向该类的一个虚成员函数。
- 每个对象增加一个指针,指向对应类的虚函数列表。此指针称为vptr。这个vptr相当于一个变量。但只由编译器自己管理(在构造、析构和复制函数中设定和重置),用户不能访问。同一个类的不同对象,将包含指向同一个vtbl的vptr,并且,不会随着对象指针类型的变化而变化
- 派生类继承后,在派生类对象的内存中,用重写的函数指针替换虚函数指针
这样利用多态,执行时就调用不同派生类的功能函数。