我有一个问题,也许你可以帮我找到解决问题的好方法.例如,我有2个结构.学生和老师都有相同的字段"名称".我想写一个函数,我可以传递给学生或老师.
struct student
{
char name[25];
unsigned int grade;
};
struct teacher
{
char name[25];
unsigned int salary[25];
};
Run Code Online (Sandbox Code Playgroud)
功能看起来像那样 -
void findAPersonNamedJohn( anyStruct &struct) {
for (int i; i < structCount; i++)
if (!strcmp(struct[i].name, "John"))
cout << "Found him!";
}
Run Code Online (Sandbox Code Playgroud)
问题是:我可以以某种方式编写提供此功能的1个功能,或者是制作2个功能的唯一方法 - 1个用于学生,1个用于教师.
谢谢
您可以使用模板功能:
template<typename T>
void findAPersonNamedJohn( const T *structs, int structCount ) {
for (int i=0; i < structCount; i++)
if (!strcmp(structs[i].name, "John"))
cout << "Found him!";
}
Run Code Online (Sandbox Code Playgroud)
或者是他们的共同基类:
struct Base {
char name[25];
};
struct student: Base {
unsigned int grade;
};
struct teacher: Base {
char salary[25];
};
void findAPersonNamedJohn( const Base **structs, int structCount ) {
for (int i=0; i < structCount; i++)
if (!strcmp(structs[i]->name, "John"))
cout << "Found him!";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |