将类数组传递给函数
Passing an array of classes to a function
我在将一个类数组传递给一个需要对类成员进行操作的函数时遇到了困难,下面的代码应该会解释我的意思。
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;
}
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中