将类数组传递给函数

Passing an array of classes to a function

本文关键字:函数 数组      更新时间:2023-10-16

我在将一个类数组传递给一个需要对类成员进行操作的函数时遇到了困难,下面的代码应该会解释我的意思。

class Person {
  public:
    char szName[16];
};

void UpdatePeople(Person* list) //<- this is the problem.
{
    for (int i=0;i<10;i++)
    {
        sprintf(&list[i]->szName, "whatever");
    }
}
bool main()
{
    Person PeopleList[10];
    UpdatePeople(&PeopleList);
    return true;
}

您不需要&,您可以直接传递数组

UpdatePeople(PeopleList);

在这个调用中,PeopleList将衰变成Person*

然后在你的UpdatePeople函数中你可以使用

for (int i=0;i<10;i++)
{
    sprintf(list[i].szName, "whatever");
}
但是,我建议使用c++标准库
#include <iostream>
#include <string>
#include <vector>
class Person{
public:
    std::string szName;
};
void UpdatePeople(std::vector<Person>& people)
{
    for (auto& person : people)
    {
        std::cin >> person.szName;
    }
}
bool main()
{
    std::vector<Person> peopleList(10);
    UpdatePeople(peopleList);
    return true;
}