代码之家  ›  专栏  ›  技术社区  ›  bashburak

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

  •  1
  • bashburak  · 技术社区  · 6 年前

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

    我的意思是,不要为结构的每个成员创建单独的函数,而是通过函数参数来确定成员(示例:&tests,lessons.examples)

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

    我想理解的是:有没有其他方法可以不写结构成员的名字就调用它?

    #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;
        }
    

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   StoryTeller - Unslander Monica    6 年前

    是的,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);
    
        2
  •  0
  •   smac89    6 年前

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

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

    在里面 random_notes 函数,只需使用 lsn 实例,它将为您提供要填充的数组