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中的接口函數實現。

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM