gpt4 book ai didi

c++ - 传递一个对象及其方法之一作为参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:32:19 25 4
gpt4 key购买 nike

我有一个包含一些算法的模型,我必须以不同的方式多次测试这些算法。仅出于测试目的(在这么多文件中)更改类中的任何内容对我来说非常困难。我想告诉编译器在哪个对象上运行哪个方法。每次,我都有两种算法进行比较,并且我有超过 10 个测试文件管理器 test1.cpp ... test10.cpp ...。因此很难调整每个测试文件。每个文件中算法的名称也不同。我正在寻找一种将方法从 main 传递给 profiler 的方法。事实上,一切都只能从 main 进行调整。我只将算法复制/粘贴到模型类中,然后修复主函数而不更改类中的任何内容(在复制/粘贴算法之后)或配置文件函数。下面的代码显示了我所需要的。随意调整此代码的结构,而无需将模型类分成两个类。我必须只留一节课。

请不要将这个问题发送(迁移)到代码审查,因为它是一个代码草案(上次我因为某人的错误而得到这么多反对票。)

欢迎提出最简单、最易读的建议。

#include <iostream>

class CModel
{
public:
// ....
// ....
// ....

CModel()
{
}

double algorithm1()
{
double result=0;
// ...
return result;
}


double algorithm2()
{
double result=0;
// ...
return result;
}

};

void profiler(CModel &model,double (*algorithm)(void))
{
// CTimer mytimer;
// mytimer.start();
// using model fields here
double result=model.(*algorithm)();
// mytimer.stop();
std::cout<<"out: "<<result<<std::endl;
// std::cout<<"time elapsed: "<<mytimer.duration;
}

int main()
{
CModel m1, m2;
// m1.something= something else;
// m2.something= something else;
profiler(m1,m1.algorithm1); // *** impossible ***
profiler(m2,m2.algorithm2); // *** impossible ***
return 0;
}

最佳答案

  1. 需要声明函数才能带成员函数

    void profiler(CModel &model, double (CModel::*algorithm)())
  2. 您需要向函数传递一个指向成员函数的指针

    profiler(m1, &CModel::algorithm1);
    profiler(m2, &CModel::algorithm2);
  3. 需要正确调用成员函数

    double result = (model.*algorithm)();

参见 C++, function pointer to member function了解更多详情。

关于c++ - 传递一个对象及其方法之一作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com