通过函数参数确定结构体成员

Determine the struct member through function parameter

本文关键字:结构体 成员 参数 函数      更新时间:2023-10-16

我想创建一个函数,它将分配结构数组的值,并通过其参数确定结构体的成员。

我的意思是,与其为结构的每个成员创建单独的函数,不如通过函数参数确定成员(示例:&.tests,课程.exams)

写下的代码 ı 仅用于解释我的意思,值可以从文本文件中导入,而不是随机分配它们。

我想了解的是;有没有其他方法可以在不写其名称的情况下调用结构成员?

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct lsn
{
    char name[20];
    int tests[4];
    int quizzes[4];
    int exams[4];
    int finals[4];
};
void random_notes(lsn *x, int *y)
{
    int i,j;
    for(i=0;i<20;i++)
        for(j=0;j<4;j++);
            x[i].y[j]=rand()%101;
}
int main()
{
    srand(time(NULL));
    lsn lessons[30];
    random_notes(lessons, &.tests);
    random_notes(lessons, &.quizzes);
    random_notes(lessons, &.exams);
    random_notes(lessons, &.finals);
    return 0;
}

而不是创建 4 个函数如下,

void random_tests(lsn *x)
    {
        int i,j;
        for(i=0;i<20;i++)
            for(j=0;j<4;j++);
                x[i].tests[j]=rand()%101;
    }
void random_quizzes(lsn *x)
    {
        int i,j;
        for(i=0;i<20;i++)
            for(j=0;j<4;j++);
                x[i].quizzes[j]=rand()%101;
    }
void random_exams(lsn *x)
    {
        int i,j;
        for(i=0;i<20;i++)
            for(j=0;j<4;j++);
                x[i].exams[j]=rand()%101;
    }
void random_finals(lsn *x)
    {
        int i,j;
        for(i=0;i<20;i++)
            for(j=0;j<4;j++);
                x[i].finals[j]=rand()%101;
    }

只有一个通过其参数确定结构成员的函数,

void random_notes(lsn *x, .struct_member y)
    {
        int i,j;
        for(i=0;i<20;i++)
            for(j=0;j<4;j++);
                x[i].y[j]=rand()%101;
    }

在这个例子中,函数非常小,但想象一个函数中一个巨大的代码,只有结构体成员不同,其余代码是相同的。

是的,C++有一个"指向成员的指针"的概念。这将允许您传递要初始化的成员的身份。但是语法有点不稳定,所以要小心:

void random_notes(lsn *x, int (lsn::* y)[4])
{
    int i,j;
    for(i=0;i<20;i++)
        for(j=0;j<4;j++);
            (x[i].*y)[j]=rand()%101; // << Access the member of x[i] via y
}

这是这样称呼的:

random_notes(lessons, &lsn::tests);

传递一个函数,该函数在调用时返回相应的结构成员。例如:

random_notes(lessons, [=](lsn& lesson) { return lesson.quizzes; });

random_notes函数中,您只需使用 lsn 实例调用该函数,它就会为您提供要填充的数组