【C++ Primer 第15章】抽象基类

 抽象基类

【注意】我们也可以为纯虚函数提供定义,不过函数体必须在类的外部,也就是说,我们不能再内部为一个=0思网函数提供函数体。

C++中含有(或未覆盖直接继承)纯虚函数的类是抽象基类,抽象基类负责定义接口,而后续的的其他类可以覆盖接口。我们不能直接出创建一个抽象基类的对象。

  C++中的纯虚函数更像是“只提供申明,没有实现”,是对子类的约束,是“接口继承”。

  C++中的纯虚函数也是一种“运行时多态”。

1 class A
2 {
3 public:
4     virtual void out1(string s) = 0;
5     virtual void out2(string s)
6     {
7         cout << "A(out2):" << s <<endl;
8     }
9 };

 程序综合实例:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class A
 5 {
 6 public:
 7     virtual void out1() = 0;
 8     virtual ~A() {};
 9     virtual void out2()
10     {
11         cout << "A(out2)" << endl;
12     }
13 
14     void out3()
15     {
16         cout << "A(out3)" << endl;
17     }
18 };
19 
20 class B :public A
21 {
22 public:
23     virtual ~B() {};
24     void out1()
25     {
26         cout << "B(out1)" << endl;
27     }
28 
29     void out2()
30     {
31         cout << "B(out2)" << endl;
32     }
33 
34     void out3()
35     {
36         cout << "B(out3)" << endl;
37     }
38 };
39 
40 int main()
41 {
42     A *ab = new B;
43     ab->out1();
44     ab->out2();
45     ab->out3();
46 
47     cout << "************************" << endl;
48 
49     B *bb = new B;
50     bb->out1();
51     bb->out2();
52     bb->out3();
53 
54     delete ab;
55     delete bb;
56     return 0;
57 }

输出结果:

15.4节练习

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9118834.html
今日推荐