c - 相同的功能,但传递给函数的参数不同

标签 c polymorphism function-pointers

struct student {

    char            *s_name;

    struct student_id   s_id;

    /** Number of references to this student. */
    unsigned int         s_ref;

    /** Transcript (singly-linked list, NULL terminator). */
    struct transcript_entry *s_transcript;

    /** Whether or not this student has completed his/her program. */
    student_complete     s_complete;
};

struct student* student_grad_create(const char *name, size_t namelen,
    struct student_id, int phd);

struct student* student_undergrad_create(const char *name, size_t namelen,
    struct student_id);

学生分为三种,硕士生、博士生和本科生。我需要实现一个函数,调用:

int student_add_entry(struct student *, struct transcript_entry *);

我不知道如何确定学生类型?

我应该执行以下操作吗?

int student_add_entry(struct student *undergrad_create, struct transcript_entry *){}
int student_add_entry(struct student *grad_create, struct transcript_entry *){}

谢谢。

最佳答案

你可以在结构中添加一个student_type字段

struct student {
    char                    *s_name;
    struct student_id        s_id;
    /** Number of references to this student. */
    unsigned int             s_ref;
    /** Transcript (singly-linked list, NULL terminator). */
    struct transcript_entry *s_transcript;
    /** Whether or not this student has completed his/her program. */
    student_complete         s_complete;
    enum student_type        s_type;
};

你会得到一个枚举,比如

enum student_type
{
    UndergraduateStudent,
    MasterStudent,
    PHDStudent
};

在创建 struct student 的实例时,您将设置 s_type 字段,然后在其他任何地方使用 s_type 来确定学生的类型.

我还会编写一个通用函数来创建 struct student 的实例并向其传递所有可能的参数,如果您想要方便,您还可以为每个特定类型创建一个函数,您可以在其中可能会将默认参数传递给通用函数。

关于c - 相同的功能,但传递给函数的参数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012082/

相关文章:

C++优雅模板注入(inject)接口(interface)

python - Python 中的多态性和类型提示

c - void *(*routine)(void *) 在 C 中是什么意思?

c - 在linux c中使用深度优先搜索遍历目录

c - 如何将 RGB 图像数组从 sws_scale 转换为 DIB(在内存位图中)

c - windows下C语言中数据的字节表示。大端和小端

c - 应为 'void (**)(void *, const char *)' 但参数类型为 'void (*)(void *, const char *)

c - 只有在进入函数时堆栈才会增长吗?

c++ - 使用多态性重载 << 运算符

c++ - for_each 中使用的函数的默认值