简体   繁体   English

将结构传递给功能

[英]Passing structure to function

I have a function in c++ that needs a structure to work, but I have a hard time passing it. 我在C ++中有一个函数,它需要一种结构才能工作,但是我很难传递它。 The structure looks like this: 结构如下:

struct RecAbbo{
    char name[20];
    char surname[20];
    int games;
    int won;
    int same;
    int lost;
    int place;
    int money;
}Abbo[100];

First I tried this: 首先,我尝试了这个:

void function(structure_name);

That did not work so I searched the internet. 那没有用,所以我搜索了互联网。 I found that you should do it like this: 我发现您应该这样做:

void function(structure_name struct);

But it didn't work. 但这没有用。

How do I do it? 我该怎么做?

It should be other way around 应该是其他方式

void function(struct RecAbbo structure_name)

Also, make sure your struct is defined before the prototype of the function function as the prototype uses it. 另外,请确保在函数使用函数原型之前定义了结构。

But in C++, you don't need to use struct at all actually. 但是在C ++中,实际上根本不需要使用struct。 So this can simply become: 这样就可以简单地变成:

void function(RecAbbo structure_name)

First of all, I think you should use std::string for both name and surname , and also use std::array for the Abbo array: 首先,我认为您应该对namesurname使用std::string ,对于Abbo数组也应该使用std::array array:

struct RecAbbo {
    std::string name;
    std::string surname;
    int games;
    int won;
    int same;
    int lost;
    int place;
    int money;
};
std::array<RecAbbo, 100> Abbo;

you can declare a function func that accepts a RecAbbo by reference or by const reference: 您可以通过引用或const引用声明一个接受RecAbbo的函数func

void func(RecAbbo&);
void func(RecAbbo const&);

The latter is recommended if you are not planning on modifying the struct . 如果您不打算修改struct则建议使用后者。

If you want to pass the array, you can use: 如果要传递数组,可以使用:

void func(std::array<RecAbbo, 100>&);
void func(std::array<RecAbbo, 100> const&);

or generalize it with iterators : 或使用迭代器将其概括化:

template<class It>
void func(It begin, It end);

or with templates: 或使用模板:

template<std::size_t Size>
void func(std::array<RecAbbo, Size>&);

template<std::size_t Size>
void func(std::array<RecAbbo, Size> const&);

Use 采用

void function(RecAbbo any_name_for_object);

This will work. 这将起作用。

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

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