欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

C++纯虚函数(接口类)的使用

程序员文章站 2022-08-07 09:05:56
C++接口类,也就是我们平时说的纯虚函数。 纯虚函数不能定义实类,只能定义指针,被用来作为接口使用。 接下来我们设计三个类:类A,类B,类C 类C是一个纯虚函数,我们将类C作为类A和类B沟通的桥梁。 1 #ifndef A_H 2 #define A_H 3 #include "C.h" 4 5 c ......

c++接口类,也就是我们平时说的纯虚函数。

纯虚函数不能定义实类,只能定义指针,被用来作为接口使用。

接下来我们设计三个类:类a,类b,类c

类c是一个纯虚函数,我们将类c作为类a和类b沟通的桥梁。

 1 #ifndef a_h
 2 #define a_h
 3 #include "c.h"
 4 
 5 class a
 6 {
 7     c* m_handler = null;
 8 public:
 9     void sethandler(c* handler = null)
10     {
11         m_handler = handler;
12     }
13 
14     void fun()
15     {
16         if(m_handler != null)
17         {
18             m_handler->func(123, "a::fun()");
19         }
20     }
21 };
22 
23 #endif // a_h
 1 #ifndef c_h
 2 #define c_h
 3 #include <qstring>
 4 class c
 5 {
 6 public:
 7     virtual void func(qint64 a, qstring s) = 0;
 8 };
 9 
10 #endif // c_h
 1 #ifndef b_h
 2 #define b_h
 3 #include "c.h"
 4 
 5 class b : public c
 6 {
 7     c* m_handler;
 8 public:
 9     void func(qint64 a, qstring s)
10     {
11         qint64 aa = a;
12         qstring ss = s;
13         qdebug() << aa;
14         qdebug() << ss;
15     }
16 };
17 
18 #endif // b_h

main函数

 1 #include <qcoreapplication>
 2 #include "a.h"
 3 #include "b.h"
 4 #include "c.h"
 5 
 6 //现在想将a b两个类通过c类(接口类)联系起来
 7 int main(int argc, char *argv[])
 8 {
 9     qcoreapplication a(argc, argv);
10 
11     a aa;
12     b b;
13 
14     aa.sethandler(&b);
15     aa.fun();
16 
17     return a.exec();
18 }

技术总结:

1、在class a中要提供设置接口的函数。

2、使用时要判断接口指针是否为空,就算忘记设置那也不会报错。

3、class b要继承class c,一定要将class b中的接口函数实现。