• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

C++:类:间访问函数指针(一百八十一)

武飞扬头像
Android系统攻城狮
帮助1

优质专栏:Audio工程师进阶系列原创干货持续更新中……】🚀

人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.

更多原创,欢迎关注:Android系统攻城狮

学新通

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
系列文章
更多 icon
同类精品
更多 icon
继续加载