// A2.5.cpp : Defines the entry point for the console application. // // Please provide the definition of a function that accepts a vector of // pointers to functions with the signature int func(X &x), invokes each // of the functions, and returns the sum of the computed values. #include "stdafx.h" #include #include using namespace std; class X { public: X(int i) : val(i) { } int& value() { return val; } private: int val; }; int fun1(X &x) { return x.value(); } int fun2(X &x) { return (x.value()*x.value()); } //// answer ///////////////////////////////////////////////////// typedef int(*fPtr)(X &x); int invoker(vector &vec, X &x) { int sum = 0; vector::iterator it; for(unsigned int i=0; i &vec, X &x) { vector::iterator it; int sum = 0; for(it = vec.begin(); it != vec.end(); ++it) { cout << "\n invoking function pointer returns value " << (*it)(x); sum += (*it)(x); } return sum; } ///////////////////////////////////////////////////////////////// int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam A2 - Question #5 " << "\n =======================\n"; vector vec; vec.push_back(&fun1); vec.push_back(&fun2); cout << "\n value returned by invoker = " << invoker(vec,X(5)); cout << "\n\n"; cout << "\n value returned by invoker2 = " << invoker2(vec,X(3)); cout << "\n\n"; return 0; }