在前面的博文中, 我们介绍了异质链表的实现, 在本文中, 我们将对上次的实现进行略微的改进。 之前, 我们把id放在node中, 现在, 我们尝试把id放在对象本身中, 且看代码:
#include <iostream>
using namespace std;
// 对象的id值
typedef enum
{
ErrorId = -1,
IntegerId = 1,
PointId = 2,
RectangeId = 3,
}ObjectID;
// 基类
struct Basic
{
ObjectID id;
};
// 整数类
struct Integer : public Basic
{
int a;
};
// 点类
struct Point : public Basic
{
int x;
int y;
};
// 矩形类
struct Rectangle : public Basic
{
Point point;
int width;
int height;
};
// 抽象对象的共同点, 构造成新的结点, 便于链接
typedef struct node
{
node *next;
Basic *pBasic;
}Node;
// 注意: A模块要和B模块商量好
int main()
{
/* A模块 */
// 定义三个对象并赋值
Integer i;
Point po;
Rectangle rect;
i.id = IntegerId;
i.a = 1;
po.id = PointId;
po.x = 2;
po.y = 3;
rect.id = RectangeId;
rect.point.x = 4;
rect.point.y = 5;
rect.width = 6;
rect.height = 7;
// 定义三个抽象出来的结点
Node node1;
node1.pBasic = &i;
Node node2;
node2.pBasic = &po;
Node node3;
node3.pBasic = &rext;
// 将三个结点链接起来, 便于用manager管理链表
Node manager;
Node *p = &manager;
p->next = NULL;
p->pBasic = NULL;
p->next = &node1;
node1.next = &node2;
node2.next = &node3;
node3.next = NULL;
Integer *pI = NULL;
Point *pPo = NULL;
Rectangle *pRect = NULL;
/* B模块 */
// 遍历链表
while(NULL != p->next)
{
// 基于A,B模块商量的结果, 要还原指针
switch(p->next->pBasic->id)
{
case IntegerId:
{
pI = (Integer*)(p->next->pBasic);
cout << pI->a << endl;
break;
}
case PointId:
{
pPo = (Point *)(p->next->pBasic);
cout << pPo->x << endl;
cout << pPo->y << endl;
break;
}
case RectangeId:
{
pRect = (Rectangle *)(p->next->pBasic);
cout << pRect->point.x << endl;
cout << pRect->point.y << endl;
cout << pRect->width << endl;
cout << pRect->height << endl;
break;
}
default:
{
break;
}
}
p = p->next;
}
return 0;
}
完毕。