array of pointers to functions

Hi.I'm trying to find out the solution of next task:
Create a class that contains a vector of pointers to functions, with add( ) member function to add pointers to functions. Add a run( ) function that moves through the vector and calls all of the functions.

My code have some errors.

#include <iostream>
#include<vector>
using namespace std;
typedef void (*pf)();
class A
{

vector<pf> v;
public:
void add(pf){ v.push_back(pf);}
void run(){ for(int i=0;i<v.size();i++)
v[i];
}
};
int c=1;
int d=2;
void print1(){cout<<c<<endl;}
void print2(){cout<<d<<endl;}
void(*pf1)()=print1;
void(*pf2)()=print2;

int main()
{
A a;
a.add(*pf1);
a.add(*pf2);
a.run();
getchar();
}
Please use code tags, because it makes the code easier to read.

typedef void (*pf)();

From this moment on, pf is a type.

pf is a type of pointer that can hold the address of a function such as:
void x() {}

So don't do this:

1
2
void(*pf1)()=print1;
void(*pf2)()=print2;


Simply do this instead:

1
2
3
4
5
6
7
8
9
10
11
// ...

int main()
{
    A a;

    a.add(print1);
    a.add(print2);

    // ...
}


Now both your A::add() and A::run() functions have mistakes:

1
2
3
4
5
6
7
8
9
10
void add(pf func)
{
    v.push_back(func);
}

void run()
{
    for(int i=0;i<v.size();i++)
        (v[i])(); // function call
}

1
2
3
4
void add(pf){ v.push_back(pf);}
// Take a simplre class does not have function pointers, but integers
// Does this look sane:
void add( int ) { v.push_back( int );}

No.

Why not a.add( print1 );?

v[i]; returns a pointer. You should dereference it in order to call the function.

Style issue: C++11 has a range-based for syntax.
Thanks .Now I find out the problems.
Topic archived. No new replies allowed.