假设我有两个不同的结构:
typedef struct {
int a;
int b;
int c;
int d;
} struct_1;
typedef struct {
int a;
int b;
int e;
int f;
int g;
int h;
} struct_2;
并且它们在两种不同的算法中以相似的方式使用。我会尝试做的是用动态数组替换这两种基本不同类型的结构,并使用两个枚举来满足我实际需要的情况。目的是保留结构字段的不同名称,而不是使用数字。所以像这样:
typedef enum {
a,
b,
c,
d,
num1_fields
} struct_1_fields;
typedef enum {
a,
b,
e,
f,
g,
h
num1_fields
} struct_2_fields;
int *structure;
if(case_1) {
structure = malloc(4*sizeof(int));
} else if(case_2) {
structure = malloc(6*sizeof(int));
} else {
//something else
}
但是由于我要重新命名同一个枚举器,编译器将无法工作...有没有办法解决这个问题?
最佳答案
您可以在 C 上使用 OOP 方法:
#include <stdio.h>
#include <stdlib.h>
// forward declaration for virtual function table
struct vtable;
// base class
typedef struct {
struct vtable* tbl_;
} base;
// virtual function table
typedef struct vtable {
void(*method_for_algorithm_1_)(base* object);
void(*method_for_algorithm_2_)(base* object);
} vtable;
// algorithm 1 knowns only about base
void algorithm_1(base* p[], int size) {
for (int i = 0; i < size; i++) {
p[i]->tbl_->method_for_algorithm_1_(p[i]);
}
}
// algorithm 2 knowns only about base
void algorithm_2(base* p[], int size) {
for (int i = 0; i < size; i++) {
p[i]->tbl_->method_for_algorithm_2_(p[i]);
}
}
// struct1 is base
typedef struct {
base super_;
int a;
int b;
int c;
} struct1;
// struct2 is base
typedef struct {
base super_;
int a;
int b;
int c;
int d;
int e;
} struct2;
void struct1_method_for_algorithm1(base* object) {
struct1* s1 = (struct1*)object;
printf("struct1_method_for_algorithm1: %d %d %d\n", s1->a, s1->b, s1->c);
}
void struct1_method_for_algorithm2(base* object) {
struct1* s1 = (struct1*)object;
printf("struct1_method_for_algorithm2: %d %d %d\n", s1->a, s1->b, s1->c);
}
void struct2_method_for_algorithm1(base* object) {
struct2* s2 = (struct2*)object;
printf("struct2_method_for_algorithm1: %d %d %d %d %d\n", s2->a, s2->b, s2->c, s2->d, s2->e);
}
void struct2_method_for_algorithm2(base* object) {
struct2* s2 = (struct2*)object;
printf("struct2_method_for_algorithm2: %d %d %d %d %d\n", s2->a, s2->b, s2->c, s2->d, s2->e);
}
int main() {
{
vtable struct1vtable = {
&struct1_method_for_algorithm1,
&struct1_method_for_algorithm2
};
struct1 a[] = {
{ &struct1vtable, 10, 20, 30 },
{ &struct1vtable, 40, 50, 60 },
};
base* p[] = { &a[0], &a[1] };
algorithm_1(p, 2);
algorithm_2(p, 2);
}
{
vtable struct2vtable = {
&struct2_method_for_algorithm1,
&struct2_method_for_algorithm2
};
struct2 a[] = {
{ &struct2vtable, 10, 20, 30, 40, 50 },
{ &struct2vtable, 40, 50, 60, 70, 80 },
};
base* p[] = { &a[0], &a[1] };
algorithm_1(p, 2);
algorithm_2(p, 2);
}
return 0;
}
关于c - 不同结构的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750565/