简体   繁体   English

如何以struct作为函数参考?

[英]How to take struct as a reference to function?

I have the following struct: 我有以下结构:

struct pole{
    int sifra;              // sifra na artiklot
    string opis;            // opis na artiklot
    float cena;             // edinecna cena
    int vlez_kol;           // vlezna kolicina
    int izlez_kol;          // izlezna kolicina
    float dan_stapka;       // danocna stapka
    float iznos;            // iznos
    int datum;              // datum na vlez i izlez (GGMMDD)
};                          // maksimalen broj na artikli e 100

pole artikli[100];


void vlez_artikl(artikli[]){ // how to take the struct as reference?

}

And I'm writing a function to input elements for each element in the struct, but I don't know how to take the struct (by struct I mean the pole artikli[100] as a reference to the function? 而且我正在编写一个函数来为结构中的每个元素输入元素,但是我不知道如何采用该结构(通过结构我指的是pole artikli[100]作为对该函数的引用?

void vlez_artikl(pole &artikli){

}

//later you can call

vlez_artikl(artikli[32]);

I think you want to pass the array of structs? 我认为您想传递结构数组? If not, then timrau's answer is appropriate. 如果不是,那么timrau的答案是合适的。

To use a reference, you need to have the function know the exact type referred to, including the array dimension. 要使用引用,您需要让函数知道所引用的确切类型,包括数组维。 This is only possible with a template: 这仅适用于模板:

template <size_t N>
void vlez_artikl(pole (artikli&)[N]) { // take the struct[] by reference
    ....
}

As using templates has downsides (a template instantiation per N, N must be known at compile time, the template implementation must be exposed to the translation unit using it), it's far more common to write functions that access an array using a pointer (often with the array size passed alongside). 由于使用模板有缺点(每N个模板实例化,必须在编译时知道N,必须使用模板将模板实现公开给转换单元),因此编写使用指针访问数组的函数的情况更为常见(通常并同时传递数组大小)。 Both the following are equivalent.... 以下两项是等效的。

void vlez_artikl(pole artikli[], size_t n) ...;
void vlez_artikl(pole* artikli, size_t n) ...;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM