初学设计模式之模板方法模式

 1 /**************************************************************************
 2 ***************************************************************************
 3                                 程序案例                                 ***
 4 小时候,因为条件有限,老师经常在黑板上给出一道题,让学生先抄题,然后再写          ***
 5 答案,但是现在都是老师老师发打印好的卷子,每个人只要写出答案就行,就相当          ***
 6 于减轻了同学们抄题的重复工作                                                ***
 7                                 核心思想                                 ***
 8                 把不变的行为搬移到父类,去除子类的重复代码                    ***
 9                                                                         ***
10                                  关键点                                  ***
11 利用父类函数中的虚函数,答案延伸到不同的子类中,也就是面向对象编程三大特          ***
12 性中的多态(封装、继承和多态)                                              ***
13 ***************************************************************************
14 ***************************************************************************/
15 #include<iostream>
16 #include <string>
17 using namespace std;
18 
19 class TestPaper 
20 {
21 public:
22     void Question1()
23     {
24         cout<<"第一题:2+3等于   A:3  B: 4  C: 5  D:6"<<endl;
25         cout<<"答案:"<<Answer1()<<endl;
26     };
27     virtual string Answer1()
28     {
29         return "";
30     };
31 };
32 
33 class Student1:public TestPaper
34 {
35 public:
36     string Answer1()
37     {
38       return "第一位同学选择A";
39     }
40 };
41 
42 class Student2:public TestPaper
43 {
44 public:
45     string Answer1()
46     {
47         return "第二位同学选择B";
48     }
49 };
50 
51  int main()
52  { 
53      Student1 m_student1;
54      m_student1.Question1();
55      Student2 m_student2;
56      m_student2.Question1();
57 
58      getchar();
59      return 0;
60  }

输出:

猜你喜欢

转载自www.cnblogs.com/wuhongjian/p/11567042.html