C++:类:间访问函数指针(一百八十一)
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:C 类之间函数指针访问。
2.应用实例
v1.0
#include <iostream>
#include <string>
#include <stdio.h>
#include <functional>
using namespace std;
class ICameraService{
public:
//1.返回类型:ICameraService*; 参数类型(int, string buf).
ICameraService* test(int a, string buf){
printf("xxx----------%s(), line = %d, a = %d, buf = %s\n",__FUNCTION__,__LINE__,a,buf.c_str());
return this;
}
void print(){
printf("xxx----------%s(), line = %d\n",__FUNCTION__,__LINE__);
}
};
int main(void){
//0.函数指针返回类型为:ICameraService*,是类对象ICameraService;定义新的函数指针类型为:TCamCallback.
typedef ICameraService* (ICameraService::*TCamCallback)(int a, string buf);
//1.初始化回调函数.
TCamCallback tcb = &ICameraService::test;
//2.取出test函数地址ICameraService().*tcb.
//v1.0
ICameraService *tt = (ICameraService().*tcb)(10,"2222");
tt->print();
//v2.0: 因为函数指针类型TCamCallback返回ICameraService类型,所以可以直接调用其成员函数print.
(ICameraService().*tcb)(10,"2222")->print();
}
注意:
ICameraService Ic;
和ICameraService();
都表示构造函数.
v2.0
#include <iostream>
using namespace std;
class TEST {
public:
//函数指针返回类型为:TEST类; 函数指针定义新类型:CallBack.
typedef TEST* (TEST::*CallBack)(int);
int createComponent(int a , int b){
printf("xxx------------->%s(), line = %d, a = %d, b = %d\n",__FUNCTION__,__LINE__,a,b);
return a b;
}
};
class STU : public TEST{
public:
TEST::CallBack callback;
TEST* print(int num) {
printf("xxx------------->%s(), line = %d, num = %d\n",__FUNCTION__,__LINE__,num);
return nullptr;
}
};
int main() {
STU stu;
//stu.callback获取STU::print函数的地址
stu.callback = static_cast<TEST::CallBack>(&STU::print);
//v1.0
//*(stu.callback):表示首先取出print函数的地址; 所以stu.*(stu.callback):表示调用print回调函数.
TEST *ss = (stu.*(stu.callback))(5);
ss->createComponent(10, 20);
//v2.0
(stu.*stu.callback)(50)->createComponent(100, 200);
return 0;
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhiahibh
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
微信运动停用后别人还能看到步数吗
PHP中文网 07-22