zoukankan      html  css  js  c++  java
  • 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中的接口函数实现。

      

  • 相关阅读:
    背包九讲
    最小生成树 prime + 队列优化
    最小生成树 prime poj1287
    树状数组--转载
    O(n)求1-n的逆元
    数据结构--线段树
    博弈
    RMQ 数据结构
    BZOJ3687 计算子集和的异或和
    Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined)D Dense Subsequence
  • 原文地址:https://www.cnblogs.com/liuchl0007/p/12623226.html
Copyright © 2011-2022 走看看