如何从单独的函数调用struct?

use*_*683 1 c++ arrays parameters struct function

#include <iostream>
#include <cmath>

using namespace std;

struct workers{
    int ID;
    string name;
    string lastname;
    int date;
};

bool check_ID(workers *people, workers &guy);
void check_something(workers *people, workers &guy, int& i);

int main()
{
    workers people[5];
    for(int i = 0; i < 5; i++){
        cin >> people[i].ID;
        cin >> people[i].name;
        cin >> people[i].lastname;
        cin >> people[i].date;
        if(check_ID(people, people[i]) == true)
            cout << "True" << endl;
        else
            cout << "False" << endl;
        check_something(people, people[i], i);
    }
    return 0;
}

bool check_ID(workers *people, workers &guy){
    for(int i = 0; i < 5; i++){
        if(people[i].ID == guy.ID)
            return true;
            break;
    }
    return false;
}

void check_something(workers *people, workers &guy, int& i){
    check_ID(people, guy[i]);
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码,它不是很好的例子,但我很快写了它来代表我的问题,因为我的项目有点太大了.所以基本上,我想从一个不同的函数调用struct,我得到这个错误: error: no match for 'operator[]' in guy[i]在这一行: check_ID(people, guy[i]);在函数中check_something.

kfs*_*one 5

main,people是一个数组.您访问它的i第th个元素people[i]并尝试将其传递到check_something函数局部变量的位置guy.然后尝试取消引用guy- 这不是数组,而是单个对象实例.

int main()
{
    workers people[5];  // <-- array
Run Code Online (Sandbox Code Playgroud)

...

    check_something(people /* <-- people */, people[i] /* <-- guy */, i /* <-- i */);
Run Code Online (Sandbox Code Playgroud)

VS

void check_something(workers *people, workers &guy, int& i){
    check_ID(people, guy[i] /* <-- array access on single instance*/);
Run Code Online (Sandbox Code Playgroud)

你实际上在第一个参数中传递了数组,人物.你这里不需要"伙伴",因为它people[i]不是吗?所以你可以这样做:

void check_something(workers *people, int& i){
    worker& guy = people[i];
    check_ID(people, guy);
Run Code Online (Sandbox Code Playgroud)

要不就

void check_something(workers *people, int& i){
    check_ID(people, people[i]);
Run Code Online (Sandbox Code Playgroud)

要么

会工作,或者你可以通过

void check_something(workers* people, workers& guy) {
    check_id(people, guy);
}
Run Code Online (Sandbox Code Playgroud)

----编辑----

你的check_ID函数中也有一个类似python的bug.

   if(people[i].ID == guy.ID)
        return true;
        break;
Run Code Online (Sandbox Code Playgroud)

在Python中,这说:

if people[i].ID == guy.ID:
    return True

break
Run Code Online (Sandbox Code Playgroud)

你想要的是什么

if ( people[i].ID == guy.ID ) {
    return true;
    break;
}
Run Code Online (Sandbox Code Playgroud)

要不就

if ( people[i].ID == guy.ID )
    return true;
Run Code Online (Sandbox Code Playgroud)

(因为返回将退出该函数,之后也说没有任何意义)