使用链表来放不同类型的对象。
#pragma once
#ifndef _MY_TEST_H
#define _MY_TEST_H
#include "mylist.h"
typedef void FunA(int iVal);
typedef void FunB(char *pc);
typedef struct nodea {
struct nodea *pNext;
int key;
int id;
FunA *pfn;
} NodeA;
typedef struct nodeb {
struct nodeb *pNext;
int key;
char *pName;
FunB *pfn;
} NodeB;
#endif // !_MY_TEST_H
#if 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "myTest.h"
void funa(int val)
{
printf("fun1->val: %d\n", val);
}
void funb(char *pc)
{
printf("fun2->name: %s\n", pc);
}
void ListTraverse(Node *pList)
{
Node *pIter = pList;
NodeA *pNodeA = NULL;
NodeB *pNodeB = NULL;
if (pIter == NULL) {
return;
}
do {
printf("%d\t", pIter->key);
switch (pIter->key)
{
case 0:
printf("Node===\n");
break;
case 1:
printf("NodeA===\n");
pNodeA = (NodeA *)pIter;
pNodeA->pfn(pNodeA->id);
break;
case 2:
printf("NodeB===\n");
pNodeB = (NodeB *)pIter;
pNodeB->pfn(pNodeB->pName);
default:
break;
}
pIter = pIter->pNext;
} while (pIter != NULL);
printf("\n");
}
int main()
{
Node *pList = NULL;
Node *pNode = NULL;
NodeA *pNodeA = NULL;
NodeB *pNodeB= NULL;
pNode = (Node *)malloc(sizeof(Node));
if (pNode == NULL) {
printf("malloc error\n");
return -1;
}
pNode->pNext = NULL;
pNode->key = 0;
ListInsert2(&pList, pNode);
pNodeA = (NodeA *)malloc(sizeof(NodeA));
if (pNodeA == NULL) {
printf("malloc error\n");
return -1;
}
pNodeA->pNext = NULL;
pNodeA->key = 1;
pNodeA->id = 19900601;
pNodeA->pfn = funa;
ListInsert2(&pList, (Node *)pNodeA);
pNodeB = (NodeB *)malloc(sizeof(NodeB));
if (pNodeB == NULL) {
printf("malloc error\n");
return -1;
}
pNodeB->pNext = NULL;
pNodeB->key = 2;
pNodeB->pName = "hello world!";
pNodeB->pfn = funb;
ListInsert2(&pList, (Node *)pNodeB);
ListTraverse(pList);
getchar();
return 0;
}
#endif