C++将结构的数组作为函数参数传递

C++ Passing an array of struct as function argument

本文关键字:函数 参数传递 数组 结构 C++      更新时间:2023-10-16

C++:下面显示的代码与在函数声明和定义中同时省略关键字struct之间有什么区别?

#include <iostream>
#include <string>
struct student{
int age;
int number;
};
void printme( struct student m[]);    // if 'struct' is omitted the code works as fine
int main()
{        
student s[3];
s[0].age = 10;
s[0].number = 333;
printme(s);
return 0;
}
void printme( struct student m[]){
printf("George age and number: %d, %d n", m[0].age, m[0].number);
}

这来自C,在C中必须指定struct(或使用typedef)。在C++中,只要结构和对象不使用相同的id,就没有区别。请不要这样做,但如果你真的想这样做,那么你需要为类型写struct student,为对象写student(如果你真想混淆所有人,这不一定是学生类型)。基本上,C++编码标准倾向于建议跳过结构,并且永远不要对结构和对象使用相同的id。

请注意,您使用的是c++和,而不是c,所以这里没有区别,您可以同时使用这两个选项。

请检查以下内容:将结构传递给函数以获取更多信息。