-1

I've got a code from the class, i can't get it to work on visual studio 2015, what is the problem, and can someone help me understand this line: int Func(function F, int x) ?

int Func(function <int(int)> F, int x)
{
    return F(x)*F(x) + 1;
}
int G(int x) 
{ 
    return x + 1;
}
int main(int argc, const char * argv[])
{
    cout << "Func(G, 5) = " << Func(G, 5) << endl;
}`

why the code isn't running ?
HG9
  • 63
  • 1
  • 6
  • 1
    What is it outputting for you and what is the expected output? Just from looking at it I would expect `37` but I'm not sure if that is the correct format for C++ function pointers. – Devan Buggay Jan 20 '18 at 01:34
  • for example: function is not defined, F is not defined...am i missing something ? – HG9 Jan 20 '18 at 01:35
  • and all the problems are inside this the Func function... – HG9 Jan 20 '18 at 01:36

1 Answers1

2

Make sure you are including the functional header and using the correct namespaces.

https://en.wikipedia.org/wiki/Function_pointer#In_C++

#include <iostream>
#include <functional>

int Func(const std::function<int(int)> F, int x)
{
    return F(x)*F(x) + 1;
}

int G(int x) 
{ 
    return x + 1;
}

int main(int argc, const char * argv[])
{
    std::cout << "Func(G, 5) = " << Func(G, 5) << std::endl;
}
Devan Buggay
  • 2,717
  • 4
  • 26
  • 35
  • 2
    `std::` is what is called the standard namespace. Most of everything in the standard library is under this namespace. You can remove the need for this by specifying you always want the standard namespace with `using namespace std;` but there are pros and cons with that solution. Take a look here: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Devan Buggay Jan 20 '18 at 01:45