C 语言里面的多态

#if 1

//一C语言中使用宏来实现多态性

#include

#define MAX(a, b)  (((a) > (b)) ? (a) : (b))

int main()
{
 int res1;
 double res2;

 res1 = MAX(5, 9);
 res2 = MAX(5.6, 4.99);
 printf("The max of 5 and 9 is : %d/n", res1 );
 printf("The max of 5.5 and 4.9 is : %f/n",res2  );
 return 0;
}
/*
The max of 5 and 9 is : 9
The max of 5.5 and 4.9 is : 5.600000
Press any key to continue
*/

#endif

#if 0

//二 C语言中使用指针实现的多态性
/* QSORT.C: This program reads the command-line
* parameters and uses qsort to sort them. It
* then displays the sorted arguments.
*/

#include
#include
#include

//void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );

int compare( const void *arg1, const void *arg2 );

void main( int argc, char **argv )
{
 int i;
 /* Eliminate argv[0] from sort: */
 argv++;
 argc--;
 
 /* Sort remaining args using Quicksort algorithm: */
 qsort( (void *)argv, (size_t)argc, sizeof( char * ), compare );
 
 /* Output sorted list: */
 for( i = 0; i < argc; ++i )
  printf( "%s ", argv[i] );
 printf( "/n" );
}

int compare( const void *arg1, const void *arg2 )
{
 /* Compare all of both strings: */
 return _stricmp( * ( char** ) arg1, * ( char** ) arg2 );
}
#endif

#if 0

#include
#include
#include

#define  MAX_NUMS 5

void qsort( void *base, size_t num, size_t width, int (__cdecl *compare )(const void *elem1, const void *elem2 ) );
int vstrcmp(const void *var1, const void *var2);
int vintcmp(const void *var1, const void *var2);

int main()
{
 char *names[MAX_NUMS] = {
  "qihailong",
  "changchao",
  "lixiaorang",
  "xiyu",
  "zhangjuntao"
 };
 int ages[MAX_NUMS] = {32, 45, 76, 21, 89};
 int i = 0;

 qsort(names, MAX_NUMS, sizeof(char *), vstrcmp);
 qsort(ages, MAX_NUMS, sizeof(int), vintcmp);
 for(i = 0; i < MAX_NUMS; ++i)
 {
  puts(names[i]);
 }
 
 for(i = 0; i < MAX_NUMS; ++i)
 {
  printf("%5d,", ages[i]);
 }
 
 puts("");
 return 0;
}

int vstrcmp(const void *var1, const void *var2)
{
 return strcmp(*(char **)var1, *(char **)var2);
}

int vintcmp(const void *var1, const void *var2)
{
 return *(int *)var1 - *(int *)var2;
}
/*
changchao
lixiaorang
qihailong
xiyu
zhangjuntao
   21,   32,   45,   76,   89,
Press any key to continue
*/

#endif

#if 0

Node * Search_List(Node *node, void const *value, int (*compare)(void const *, void const *))
{
 while(node != NULL)
 {
  if(compare(&node->value, value) == 0)
  {
   break;
  }
  else
  {
   node = node->next;
  }
 }
 return node;
}

int compare_ints(void const *a, void const *b)
{
 if(*(int *)a == *(int *)b)
 {
  return 0;
 }
 else
 {
  return 1;
 }
}

#endif

//三C语言中使用结构和联合来实现多态性

你可能感兴趣的:(C/C++语言经典问题源码解析,语言,c,parameters,algorithm,list,search)