打包多个c++对象并传递给函数

pack multiple c++ objects and pass to function

本文关键字:函数 包多个 c++ 对象      更新时间:2023-10-16

我使用c库进行集成,其中被积函数被声明为fun(…,void*fdata,…)

它使用*fdata指针来传递外部变量,然而,在进行数值积分之前,我需要

使用其他c++库对原始数据进行插值,返回一些插值类对象

基本上,我想把这些对象传递给一个被积函数,它是用户定义的。。。

您可以使用一个结构并将指针传递给它,但在我看来,您没有固定数量的对象要传递,因此动态聚合其他对象会更好地满足您的需求,因此您可以使用std::vector并将其地址作为func fdata参数传递。

一个例子:

#include <vector>
#include <iostream>
using namespace std;
class C //Mock class for your objs
{
public:
  C(int x)
  {
    this->x = x;
  }
  void show()
  {
    cout << x << endl;
  }
private:
  int x;
};
void func(void *fdata) //Your function which will recieve a pointer to your collection (vector)
{
  vector <C *> * v = (vector<C *> *)fdata; //Pointer cast
  C * po1 = v->at(0);
  C * po2 = v->at(1);
  po1->show();
  po2->show();
}

int main()
{
  vector<C *> topass;
  topass.push_back(new C(1)); //Create objects and add them to your collection (std::vector)
  topass.push_back(new C(2));
  func((void *)(&topass)); //Call to func
  for(vector<C *>::iterator it = topass.begin(); it != topass.end(); it++)
      delete(*it);
}