打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

  

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
“undefined reference to” 问题汇总及解决方法
头文件互相包含
C++ 关于声明,定义,类的定义,头文件作用,防止头文件在同一个编译单元重复引用,不具名空间
C 如何调用写好的C接口?
[Chrome源码阅读]IPC通信初探
Golang构建HTTP服务(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服