将结构传递给void函数

Bor*_*nko 1 c++ file-io struct pass-by-reference void

我的问题是如何将struct.variable(或结构数组)传递给void函数.基本上代码如下:

结构

struct Person{
    string surname;
    string BType;
    string organ;
    int age;
    int year, ID, IDp;
} Patient[50], Donor[50];

int i; // counter variables for the arrays such as Patient[i].BType... etc
int i1; 
Run Code Online (Sandbox Code Playgroud)

那么函数的代码是这样的一行:

void compare(int &i, int &i1, Person &Patient[50], Person &Donor[50]);
Run Code Online (Sandbox Code Playgroud)

我试图通过i,i1,PatientDonor结构.为什么这不起作用?有没有一种特殊的方法将这些结构传递给函数?

变量结构中的值也是从文件中读取的(不要认为这会改变任何内容).有任何想法吗?

Who*_*aig 5

你的函数原型是不正确的.要传递固定数组类型引用,必须限定数组索引声明之外的参数的引用部分.

void compare(int &i, int &i1, Person (&Patient)[50], Person (&Donor)[50])
//  note parens ----------------------^-------^-------------^------^
Run Code Online (Sandbox Code Playgroud)

简单地调用

compare(i, i1, Patient, Donor);
Run Code Online (Sandbox Code Playgroud)

有趣的是,您可以使用通过演绎保证固定数组大小的模板来完成此操作.

template<size_t N>
void compare(int &i, int &i1, Person (&Patient)[N], Person (&Donor)[N])
{
    // N is guarenteed to be the size of your array. You can use it
    //  as you would 50 in your code.
    for (size_t i=0; i<N;++i)
    {
        // do something with Patient and Donor elements
    }
}
Run Code Online (Sandbox Code Playgroud)

这具有允许使用不同数组大小进行实例化的附加好处.即你也可以这样做:

Person Patient[50], Donor[50];
Person MorePatients[10], MoreDonors[10];

....

compare(i, i1, Patient, Donor);
compare(i, i1, MorePatients, MoreDonors)
Run Code Online (Sandbox Code Playgroud)

它会正确编译.我建议你试一试,你可能会发现它很有用.