C++/Function/Function Pointer

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Assigning function pointers to overloaded functions

 
#include <iostream>
using namespace std;
void space(int count) 
{
  for( ; count; count--) 
     cout << " ";
}
void space(int count, char ch) 
{
  for( ; count; count--) 
     cout << ch;
}
int main()
{
  void (*functionPointer1)(int);
  void (*functionPointer2)(int, char);
  functionPointer1 = space;                  // gets address of space(int)
  functionPointer2 = space;                  // gets address of space(int, char)
  functionPointer1(22);                      
  cout << "|\n";
  functionPointer2(30, "x");                 
  cout << "|\n";
  return 0;
}


Pointer for empty string

  
#include <functional>
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void findEmptyString(const vector<string*>& strings)
{
  vector<string*>::const_iterator it = find_if(strings.begin(), strings.end(),mem_fun(&string::empty));
  if (it == strings.end()) {
    cout << "No empty strings!\n";
  } else {
    cout << "Empty string at position: " << it - strings.begin() << endl;
  }
}
int main(int argc, char **argv)
{
  vector<string *> myVector;
  string one = "blah";
  string two = "";
  myVector.push_back(&one);
  myVector.push_back(&one);
  myVector.push_back(&two);
  myVector.push_back(&one);
  findEmptyString(myVector);
  return (0);
}


Pointers as Function Arguments

 

#include <iostream>
using namespace std;
void assignValues(int[], int);
void displayValues(int[], int);
const int MAX = 3;
int main ()
{
   int testScore[MAX];
   assignValues(testScore, MAX);
   displayValues(testScore, MAX);  
   return 0;
}
void assignValues(int tests[], int num)
{
   for (int i = 0; i < num; i++)
   {
      cout << "Enter test score #" << i + 1 << ": ";
      cin >> tests[i];
   }
}
void displayValues(int scores[], int elems)
{
 for (int i = 0; i < elems; i++)
   {
      cout << "Test score #" << i + 1 << ": "
         << scores[i] << endl;
   }
}