当前位置: 移动技术网 > 科技>操作系统>windows > C++纯虚函数(接口类)的使用

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

2020年04月13日  | 移动技术网科技  | 我要评论

爱儿教育网下载中心,qq代理服务器地址,杜拉拉升职记电子书下载

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中的接口函数实现。

  

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网