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/