欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

类成员函数作为函数参数/回调函数 出现error C3867

发布时间:2025/4/16 编程问答 32 豆豆
生活随笔 收集整理的这篇文章主要介绍了 类成员函数作为函数参数/回调函数 出现error C3867 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

转自:https://blog.csdn.net/liyunxin_c_language/article/details/83188176

 

类成员函数作为函数参数出现error C3867:非标准语法;请使用“&”来创建指向成员的指针

2018年10月19日 21:17:40 liyunxin_c_language 阅读数:2097

有的时候一个泛函可能会采用函数或函数对象(functor)做参数,这时候我们可能想要使用类的成员函数来做参数,但是这时候会出现error C3867: 非标准语法;请使用 "&" 来创建指向成员的指针,比如下面例子:

 

  • #include <iostream>
  • using namespace std;
  • class TestC
  • {
  • private:
  • double a, b;
  • public:
  • TestC(double a_,double b_):a(a_),b(b_){}
  • double testFun(double x);
  • };
  • template<class Func>
  • double testTemplateFun(double input, Func proccess)
  • {
  • return proccess(input);
  • }
  • int main()
  • {
  • double a = 10;
  • TestC t(2, 3);
  • cout << "输出结果为:" << testTemplateFun(a, t.testFun);
  • system("pause");
  • return 0;
  • }
  • double TestC::testFun(double x)
  • {
  • return a*x + b;
  • }

  • 这时候我们按照提示将t.testFun前面加上&又会出现error C2276: “&”: 绑定成员函数表达式上的非法操作,那么这到底是什么错误?

    其实这里是因为类的成员函数默认带有一个this指针参数,那么它作为泛函的参数其实就不匹配了,因为泛函中的Func类型并没有this指针,所以我们可以把TestC类中的testFun(double x)函数声明为静态(static)的,这样就不带有this指针;但是静态的函数又不能访问非静态的成员,像这里TestC的testFun函数访问了非静态的成员变量a,b,就会出错,那要怎么办?这里其实就是相当于泛函中要求单参函数,而使用的是双参函数,可以自己定义一个适配类,适配双参函数为单参,如下例:

  • #include <iostream>
  • using namespace std;
  • class TestC
  • {
  • private:
  • double a, b;
  • public:
  • TestC(double a_,double b_):a(a_),b(b_){}
  • double testFun(double x);
  • };
  • template<class Func>
  • double testTemplateFun(double input, Func proccess)
  • {
  • return proccess(input);
  • }
  • class TestCAdapter
  • {
  • private:
  • TestC *t;
  • public:
  • TestCAdapter(TestC *t_):t(t_){}
  • double operator()(double x);
  • };
  • int main()
  • {
  • double a = 10;
  • TestC t(2, 3);
  • //cout << "输出结果为:" << testTemplateFun(a, t.testFun) << endl;
  • TestCAdapter ad(&t);
  • cout << "输出结果为:" << testTemplateFun(a, ad) << endl;
  • system("pause");
  • return 0;
  • }
  • double TestC::testFun(double x)
  • {
  • return a*x + b;
  • }
  • double TestCAdapter::operator()(double x)
  • {
  • return t->testFun(x);
  • }
  • 转载于:https://www.cnblogs.com/damoying/p/10683244.html

    总结

    以上是生活随笔为你收集整理的类成员函数作为函数参数/回调函数 出现error C3867的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。