简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:C++类之间函数指针访问。文章来源:https://www.toymoban.com/news/detail-652314.html
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();
都表示构造函数.文章来源地址https://www.toymoban.com/news/detail-652314.html
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;
}
到了这里,关于C++之类之间访问函数指针(一百八十一)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!