有没有办法在具有相同功能的不同列表结构中对同一字段执行操作?
Is there a way to perform operations on the same field in different list structs with the same function?
有没有办法用相同的函数访问不同列表结构中的相同字段?
例如,像可以与不同类型一起使用的max函数:
#define MAX(a,b) (((a)>(b))?(a):(b))
然后假设我有两种不同的列表类型:
typedef struct lst1{
struct lst1 * head;
...
} LST1;
typedef struct lst2{
struct lst2 * head;
...
} LST2;
是否有与 max
函数类似的函数?
#define isempty(x) ((x->head==NULL) ? 1 : 0)
PS:isempty
对我不起作用,这是我得到的示例代码和错误:
List lst;
lst.head = NULL;
List * a = &lst;
int a = isempty(a);
error C2040: 'a' : 'int' differs in levels of indirection from 'List *'
假设你有两个列表,那么你可以如下定义它们
#include <stdio.h>
struct GenericList
{
struct GenericList *commonField;
};
struct FirstList
{
struct FirstList *commonField;
int firstListField;
};
struct SecondList
{
struct SecondList *commonField;
int secondListField;
};
int isempty(struct GenericList *list)
{
return ((list != NULL) && (list->commonField != NULL));
}
int main(void)
{
struct FirstList firstList;
struct SecondList secondList;
memset(&firstList, 0, sizeof(firstList));
memset(&secondList, 0, sizeof(secondList));
if (isempty((struct GenericList *)&firstList) == 0)
printf("The list is empty ... \n");
if (isempty((struct GenericList *)&secondList) == 0)
printf("The list is empty ... \n");
return 0;
}
只要结构定义的开头匹配,就可以对更多的字段进行匹配,这就是为什么它就像c++中的继承。
有没有办法用相同的函数访问不同列表结构中的相同字段?
例如,像可以与不同类型一起使用的max函数:
#define MAX(a,b) (((a)>(b))?(a):(b))
然后假设我有两种不同的列表类型:
typedef struct lst1{
struct lst1 * head;
...
} LST1;
typedef struct lst2{
struct lst2 * head;
...
} LST2;
是否有与 max
函数类似的函数?
#define isempty(x) ((x->head==NULL) ? 1 : 0)
PS:isempty
对我不起作用,这是我得到的示例代码和错误:
List lst;
lst.head = NULL;
List * a = &lst;
int a = isempty(a);
error C2040: 'a' : 'int' differs in levels of indirection from 'List *'
假设你有两个列表,那么你可以如下定义它们
#include <stdio.h>
struct GenericList
{
struct GenericList *commonField;
};
struct FirstList
{
struct FirstList *commonField;
int firstListField;
};
struct SecondList
{
struct SecondList *commonField;
int secondListField;
};
int isempty(struct GenericList *list)
{
return ((list != NULL) && (list->commonField != NULL));
}
int main(void)
{
struct FirstList firstList;
struct SecondList secondList;
memset(&firstList, 0, sizeof(firstList));
memset(&secondList, 0, sizeof(secondList));
if (isempty((struct GenericList *)&firstList) == 0)
printf("The list is empty ... \n");
if (isempty((struct GenericList *)&secondList) == 0)
printf("The list is empty ... \n");
return 0;
}
只要结构定义的开头匹配,就可以对更多的字段进行匹配,这就是为什么它就像c++中的继承。