【问题标题】:pack multiple c++ objects and pass to function [closed]打包多个 c++ 对象并传递给函数 [关闭]
【发布时间】:2014-09-09 06:04:48
【问题描述】:

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

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

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

基本上我想将这些对象传递给用户定义的被积函数...

【问题讨论】:

  • 你应该澄清你想要做什么。细节很重要。
  • juanchopanza 的评论是有效的 - 为了让您更好地了解相关内容,您可能会告诉我们您是否尝试传递许多相同类型的对象?为什么您使用void*s 而不是模板化函数参数或使用指向基类的指针。你为什么在问题上加上“C”标签?
  • 请不要以这种方式破坏您的问题。这对花时间在下面回答的用户完全不公平

标签: c++ c numerical


【解决方案1】:

您可以使用一个结构并传递一个指向它的指针,但在我看来,您没有固定数量的对象要传递,因此动态聚合其他对象的对象会更好地满足您的需求,因此您可以使用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);
}

【讨论】:

  • 如果有必要,为什么不用func(const std::vector&lt;C*&gt;&amp; fdata) 或 ``func(const std::vector& fdata)` - 并避免额外的演员表?
  • @TonyD 因为我理解OP的函数fdata必然是void *否则,你建议的声明更好。
  • @PabloFranciscoPérezHidalgo 我会说 OP 不知道标题中 c++ 的确切要求是什么,并且不需要标签......
猜你喜欢
  • 2021-10-05
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多