c++ - Pointer to function -
what mistakes mean? why when make types double, doesn't show same mistakes?
c2556 'int div(int,int)': overloaded function differs return type 'div_t div(int,int)'
c2371 'div': redefinition; different basic types
c2491 'div': definition of dllimport function not allowed
c2664 'int calculate(int,int,int (__cdecl *)(int,int))': cannot convert argument 3 'overloaded-function' 'int (__cdecl *)(int,int)'
#include <iostream> using namespace std; int sum(int x, int y) { return x + y; } int subs(int x, int y) { return x - y; } int mult(int x, int y) { return x * y; } int div(int x, int y) { return x / y; } int calculate(int x, int y, int(*func)(int, int)) { return func(x, y); } void main() { cout<<"sum:"<< calculate(8, 4, sum)<<endl; cout << "subs:" << calculate(8, 4, subs) << endl; cout << "mult:" << calculate(8, 4, mult) << endl; cout << "div:" << calculate(8, 4, div) << endl; }
there exists div
function in stdlib.h
standard header included iostream
, overload in conflict with.
one way use own namespace (using namespaces idea), this:
#include <iostream> namespace { int sum(int x, int y) { return x + y; } int subs(int x, int y) { return x - y; } int mult(int x, int y) { return x * y; } int div(int x, int y) { return x / y; } int calculate(int x, int y, int(*func)(int, int)) { return func(x, y); } } int main() { std::cout << "sum:" << my::calculate(8, 4, my::sum) << std::endl; std::cout << "subs:" << my::calculate(8, 4, my::subs) << std::endl; std::cout << "mult:" << my::calculate(8, 4, my::mult) << std::endl; std::cout << "div:" << my::calculate(8, 4, my::div) << std::endl; return 0; }
of course can use shorter alternative using
:
... namespace { ... } using my; ... std::cout << "sum:" << my::calculate(8, 4, sum) << std::endl; std::cout << "subs:" << my::calculate(8, 4, subs) << std::endl; std::cout << "mult:" << my::calculate(8, 4, mult) << std::endl; std::cout << "div:" << my::calculate(8, 4, my::div) << std::endl; // scoped eliminate ambiguity
Comments
Post a Comment