SmartVessel

Foucs on C++

博客园 首页 新随笔 联系 订阅 管理
#include <iostream>
#include 
<string>
using namespace std;

void male()
  {
  cout 
<< "I'm a man.\n";
  }

void female()
  {
  cout 
<< "I'm a woman.\n";
  }

struct
  {
  (
void)(*fn)();
  
const char* key;
  }
function_lookup_table[] 
=
  {
  { 
&male,   "male"   },
  { 
&female, "female" },
  { NULL,    NULL     }
  };

bool lookup_and_call( const string& name )
  {
  
for (int i = 0; function_lookup_table[ i ].fn; i++)
    
if (name == function_lookup_table[ i ].key)
      {
      (
*(function_lookup_table[ i ].fn))();
      
return true;
      }
  
return false;
  }

int main()
  {
  
string users_gender;
  cout 
<< "Enter male or female> " << flush;
  getline( cin, users_gender );
  
if (!lookup_and_call( users_gender ))
    {
    cout 
<< "What?\n";
    }
  
return 0;
  } 
posted on 2011-04-14 14:23  SmartVessel  阅读(206)  评论(0编辑  收藏  举报