“a value of type ”void (exeCallback::*)(int)“ cannot be assigned to an entity of type ”void (*)(int)“” [duplicate]

余生颓废 提交于 2021-02-16 23:04:09

问题


Possible Duplicate:
Disabling “bad function cast” warning

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?

I created two files, exeCallback.h and exeCallback.cpp.

.h file

/*
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:

/*
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 );
}

回答1:


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);

Or make your life easier by using std::function (or boost::function if you don't have C++11 support).



来源:https://stackoverflow.com/questions/13487596/a-value-of-type-void-execallbackint-cannot-be-assigned-to-an-entity-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!