Advertisement

Function pointer in C++

Started by December 01, 2007 11:26 AM
3 comments, last by Grantax 16 years, 11 months ago
Dear everybody ! I got a problem that make me crazy, I don't know how to fix. I got the file constructive.c like below:
Quote: /*constructive.c Constructive Solid Geometry*/ #include <GL/glut.h> #include <stdlib.h> #include <math.h> void firstInsideSecond(void (*a) (void), void (*b) (void), GLenum face, GLenum test) { ... } void fixDepth(void (*a) (void)) { ... } /* subtract b from a */ void sub(void (*a) (void), void (*b) (void)) { firstInsideSecond(a, b, GL_FRONT, GL_NOTEQUAL); fixDepth(b); firstInsideSecond(b, a, GL_BACK, GL_EQUAL); glDisable(GL_STENCIL_TEST); }
Then I inlude this file into main.cpp with the content below:
Quote: #include "constructive.c" class CMaSim { public: ... void Subtract(); void RenderCutter(); void RenderObject(); ... } void CMaSim::Subtract() { sub( RenderCutter, RenderObject); // <----- this line got error }
Then I run and got an error :
Quote: error C2664: 'sub' : cannot convert parameter 1 from 'void (void)' to 'void (__cdecl *)(void)
please, help me
Pointers to member functions are incompatible with pointers to ordinary functions (i.e. their types are different), and in the line where the error occurs you 're passing the "sub" method a pointer to a member function. You can have a look here:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
Advertisement
Quote: Original post by havythoai
#include <stdlib.h>#include <math.h>

These should be <cstdlib> and <cmath> if you're using C++. Also, you appear to be using this file (constructive.c) as a header, so it should be called constructive.h. The definitions for the functions will need to be moved out to a proper source file.

Quote: Original post by havythoai
class CMaSim{public:...void Subtract();void RenderCutter();void RenderObject();...}void CMaSim::Subtract(){sub( RenderCutter, RenderObject); // <----- this line got error}

RenderCutter is a member function pointer, not a regular function pointer. If you want to treat these things interchangeably (regular function pointers and member function pointers) you'll probably want to use functors to abstract the underlying mechanics. They're different types of pointers and can't be swapped as-is.
Ra
Since no one else has mentioned it yet, I'd recommend having a look at Boost.Function and Boost.Bind.
Also, shouldn't there be a semicolon after the class declaration? :)

This topic is closed to new replies.

Advertisement