爱儿教育网下载中心,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中的接口函数实现。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
win10如何启用管理员账户 win10禁用/启用管理员账户的方法
win10怎么查看驱动是否异常 Win10检测驱动程序是否正常的方法
Windows10系统任务栏无效图标怎么删除 通过注册表一键快速删除
Win10系统自动重启怎么办 Win10系统自动重启的关闭方法
怎么减少win10笔记本功耗 详谈笔记本硬件功耗大的原因和解决办法
网友评论