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

时间:2019-01-27 07:01:03

标签: c++ struct

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

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

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

我想了解的是;还有什么其他方法可以在不写其名称的情况下调用struct成员?

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

仅是一个通过其参数确定struct成员的函数,

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

在此示例中,该函数很小,但是可以想象一个巨大的代码,只有struct成员不同,其余代码相同。

2 个答案:

答案 0 :(得分:1)

是的,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);

答案 1 :(得分:0)

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

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

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