可能重复: 禁用不良功能转换"警告
我试图用我的脑袋围绕c ++函数指针.为了保持基本的学习经验,我创建了一个测试函数指针示例.最终,我想通过引用传递所有现成的实例化对象,以便我可以回调该对象的方法.但是,为了学习和理解,我想坚持使用c ++函数指针的基础知识.我仅使用.cpp文件创建了一个工作示例,但我未成功完成的部分是在.cpp和.h中使用了函数指针.使用.cpp和.h文件时,要使我的学习示例成功工作,我该怎么做?
I am attempting to wrap my brain around c++ function pointers. To keep my learning experience basic, I created a test function pointer example. Eventually, I would like to pass all-ready instantiated objects by reference so I can callback the object's method; however, for the sake of learning and understand, I would like to stick to the basics of c++ function pointers. I created a working example just using a .cpp file, but the part that I am not succeeding at is using function pointers in .cpp and .h. What am I not doing correctly to get my learning example to work successfully when using .cpp and .h files?
我创建了两个文件exeCallback.h和exeCallback.cpp.
I created two files, exeCallback.h and exeCallback.cpp.
.h文件
/* File: exeCallback.h Header file for exeCommand Library. */ #ifndef EXECALLBACK_H #define EXECALLBACK_H #include "mbed.h" #include <map> class exeCallback { public: exeCallback(); void my_int_func(int x); void (*foo)(int); private: }; #endif.cpp文件:
/* File: exeCallback.cpp Execute functions in other Sensor libraries/classes Constructor */ #include "mbed.h" #include "ConfigFile.h" #include "msExtensions.h" #include "cfExtensions.h" #include "exeCallback.h" exeCallback::exeCallback() { foo = &exeCallback::my_int_func; /* call my_int_func (note that you do not need to write (*foo)(2) ) */ foo( 2 ); } void exeCallback::my_int_func(int x) { printf( "%d\n", x ); } 推荐答案该错误告诉您正在尝试将成员函数的指针分配给(非成员)函数的指针.有关差异的更多信息,请参见[here](错误告诉您正在尝试将成员函数的指针分配给(非成员)函数的指针.)看来您需要将 foo 声明为
The error is telling you that you are trying to assign a pointer to a member function to a pointer to a (non-member) function. See [here](The error is telling you that you are trying to assign a pointer to a member function to a pointer to a (non-member) function.) for more on the differences. It looks like you need to declare foo as
void (exeCallback::*foo)(int);或者通过使用 std :: function 来使您的生活更轻松代码> (如果没有C ++ 11支持,则为 boost :: function ).
Or make your life easier by using std::function (or boost::function if you don't have C++11 support).
更多推荐
“类型为"void(exeCallback :: *)(int)"的值"不能将其分配给类型为"void(*)(int)&
发布评论