C++ 指向其他类函数的指针函数

C++ Pointer function to other class function

本文关键字:指针 函数 类函数 其他 C++      更新时间:2023-10-16

我需要帮助在C++上传递函数指针。我无法将一个类的一个函数链接到另一个函数。我会解释的。无论如何,我将放置我的程序的代码简历,它比此处公开的代码大得多,但为了更容易,我只放置我需要的部分,它可以正常工作。

我有一个类(MainSystem(,里面有一个指向另一个类的对象指针(ComCamera(。最后一个类是SocketServer,我希望当套接字收到任何数据时,它会发送到主系统的链接函数。

ComCamera 是与更多类共享的资源,我需要将函数 ComCamera::vRecvData 关联到 MainSystem::vRecvData 或其他类的其他函数,以便在接收数据并将 de 数据发送到函数类关联时进行调用。

谁能帮我?

EDDITED - 以下解决方案

主.cpp

#include <iostream>
#include <thread>  
#include <string>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <exception>
#include <unistd.h>
using std::string;
class ComCamera {
public:
std::function<void(int, std::string)> vRecvData;
void vLinkRecvFunction(std::function<void(int, std::string)> vCallBack) {
this->vRecvData = vCallBack;
}
void vCallFromCamera() {
this->vRecvData(4, "Example");
};
};
class MainSystem {
private:
ComCamera *xComCamera;
public:
MainSystem(ComCamera *xComCamera) {
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iChannelNumber, std::string sData) {vRecvData(iChannelNumber, sData); });
}
void vRecvData(int iNumber, string sData) {
std::cout << "RECV Data From Camera(" + std::to_string(iNumber) + "): " << sData << std::endl;
};
};
int main(void) {
ComCamera xComCamera;
MainSystem xMainSystem(&xComCamera);
xComCamera.vCallFromCamera();
return 0;
}

输出将是:

来自相机的主系统RECV数据(4(:示例

你可以ComCamera::vRecvData

类型为std::function<void(int, std::string)>,然后ComCamera::vLinkRecvFunction()如下所示

void ComCamera::vLinkRecvFunction(std::function<void(int, std::string)> callBack)
{
this->vRecvData = callBack;
}

并且MainSystem构造函数如下所示:

MainSystem::MainSystem(ComCamera *xComCamera)
{
using namespace std::placeholders;
this->xComCamera = xComCamera;
this->xComCamera->vLinkRecvFunction([this](int iNumber, std::string sData){vRecvData(number, sData);});
}

尽管如此,尽管原始问题的代码太多,无法通过朋友。

在这里你想要的:

#include<iostream>
using std::cout;
class A; //forward declare A
class B{
public:
void (A::*ptr)(int x); //Only declare the pointer because A is not yet defined.
};
class A{
public:
void increase_by(int x){
a+=x;
} // this function will be pointed by B's ptr
int a = 0; // assume some data in a;
B b; // creating B inside of A;
void analyze(int y){ 
(*this.*(b.ptr))(y);
}   // Some function that analyzes the data of A or B; Here this just increments A::a through B's ptr           
};
int main(){
A a; // creates A
cout<<a.a<<"n"; // shows initial value of a
a.b.ptr = &A::increase_by; // defines the ptr that lies inside of b which inturns lies inside a
a.analyze(3); // calls the initialize method
(a.*(a.b.ptr))(3); // directly calls b.ptr to change a.a
cout<<a.a; // shows the value after analyzing
return 0;
}

输出将为:

0

6

我仍然不明白你为什么要做这样的事情。但也许这就是您想要的根据您的评论。 要了解更多信息,请阅读此精彩的PDF。