如何将任何结构传递给函数?

3

我有一个问题,也许你能帮我找到一个好的解决方法。比如我有两个结构体,学生和老师都有一个相同的字段“姓名”。我想编写一个函数,可以传递学生或教师。

struct student
{
    char name[25];
    unsigned int grade;
};

struct teacher
{
    char name[25];
    unsigned int salary[25];
};

这个函数看起来大概是这样的 -

void findAPersonNamedJohn( anyStruct &struct) {
  for (int i; i < structCount; i++)
    if (!strcmp(struct[i].name, "John"))
      cout << "Found him!";
}

问题是:我能否编写一个函数来提供这个功能,还是必须制作两个函数 - 一个用于学生,另一个用于教师。
谢谢。

2
为什么要使用char []数组来存储名称?在C++中,您可以使用“std :: string”,这比使用char[]数组方便100倍。另外我假设薪水是一个数字,那么为什么要使用字符串类型呢? - LibertyPaul
@LibertyPaul,是的-字符串更有意义,谢谢!薪水只是我的错误,我会纠正它。我会保留char,这样人们就不必更改他们的答案了。 - Deniss
2个回答

7
您可以使用模板函数:
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!";
}

或者为它们创建一个共同的基类:

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!";
}

不!基类示例是未定义的行为,并且在任何可能的方式上都是完全错误的。如果没有意义,那么模板是正确的。 - Puppy
这到底是什么未定义行为?你是在暗示任何形式的继承都是未定义行为吗? - user975989
@Puppy 对的,切片。从上面复制并粘贴。已更新。 - skypjack
我无法在良心上好好地取消我的踩票,因为那个原始指针数组索引的狗屎仍然存在。 - Puppy
@Puppy 我并没有要求你取消你的踩,所以我不知道你为什么要提到它。我只是更新了问题而已。感谢你注意到了错误。 - skypjack

2

这是一个很好的使用 继承 的情况示例。如果你有两个类(或结构体)具有相同的字段,你可以将这部分从这些类中移到基类,并从它们中都继承:

struct human{
    char name[25];
};

struct student : public human
{
    unsigned int grade;
};

struct teacher : public human
{
    char salary[25];
};

所以studentteacher都将有一个名为name的字段。

并将基类的引用传递到函数中:

void findAPersonNamedJohn(const human &human) {
    if (!strcmp(human.name, "John"))
      cout << "Found him!";
}

这个函数并不知道实际对象的类型,它只知道传递了一个类型为 human 的对象。

int main(){

    student s1;
    strcpy(s1.name, "John");
    s1.grade = 1;

    teacher t1;
    strcpy(s1.name, "Alice");
    s1.grade = 2;

    findAPersonNamedJohn(s1);
    findAPersonNamedJohn(t1);
}

@WhatsUp 这是作者的代码。在字符串中存储数字为什么不好是另一个问题的主题。 - LibertyPaul
不行,这将是非常未定义的行为。 - Puppy
@Puppy你能解释一下在哪里以及为什么吗? - LibertyPaul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接