C++_练习—多态_纯虚函数与抽象类

纯虚函数与抽象类


 

含有纯虚函数的类,称为抽象基类,不可实列化。即不能创建对象,存在的意义就是被继承,提供族类的公共接口。

 

 1 // 纯虚函数与抽象类
 2 
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 class shape {
 8 public:
 9     virtual double getarea() = 0;
10 };
11 
12 class cfx :public shape {
13 public:
14     cfx(int a, int b) {
15         this->a = a;
16         this->b = b;
17     }
18 
19     virtual double getarea() {
20         cout << "cfx =  " << a*b << endl;
21         return a * b ;
22     }
23 
24 private:
25     int a;
26     int b;
27 };
28 
29 class yx :public shape {
30 public:
31     yx(int r) {
32         this->r = r;
33     }
34 
35     virtual double getarea() {
36         cout << "yx =  " <<  3.14*r*r << endl;
37         return 3.14*r*r;
38     }
39 
40 private:
41     int r;
42 };
43 
44 int main(void)
45 {
46     shape *changfx = new cfx(2,3);
47     changfx->getarea();
48 
49     shape *yuan = new yx(1);
50     yuan->getarea();
51 
52     system("pause");
53 
54     return 0;
55 }

 

 

笔记


 

posted @ 2019-08-20 11:12  panda_w  阅读(246)  评论(0编辑  收藏  举报