原文: https://www.programiz.com/cpp-programming/structure-function
可以使用与普通参数类似的方式将结构变量传递给函数。 考虑以下示例:
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
void displayData(Person); // Function declaration
int main()
{
Person p;
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
// Function call with structure variable as an argument
displayData(p);
return 0;
}
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}输出
Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4在该程序中,要求用户在main()函数内输入人员的name,age和salary。
然后,将结构变量p传递给使用。
displayData(p);displayData()的返回类型是void,并且传递了类型结构Person的单个参数。
然后从该函数显示结构p的成员。
#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float salary;
};
Person getData(Person);
void displayData(Person);
int main()
{
Person p;
p = getData(p);
displayData(p);
return 0;
}
Person getData(Person p) {
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
return p;
}
void displayData(Person p)
{
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
} 该程序的输出与上面的程序相同。
在该程序中,在main()函数下定义了类型为Person的结构变量p。
结构变量p传递给getData()函数,该函数从用户那里获取输入,然后返回到主函数。
p = getData(p); 注意:如果两个结构变量的类型相同,则可以使用赋值运算符=将结构变量的所有成员的值分配给另一个结构。 您无需手动分配每个成员。
然后将结构变量p传递给displayData()函数,该函数显示信息。