English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在本文中,您将找到相关示例,将结构体作为参数传递给函数,并在程序中使用它们。
可以像普通参数一样将结构体变量传递给函数。考虑以下示例:
#include <iostream> using namespace std; struct Person { char name[50]; int age; float salary; }; void displayData(Person); // 声明函数 int main() { Person p; cout << "输入姓名: "; cin.get(p.name, 50); cout << "输入年龄: "; cin >> p.age; cout << "输入工资: "; cin >> p.salary; // 函数调用,结构变量作为参数 displayData(p); return 0; } void displayData(Person p) { cout << "\n显示信息" << endl; cout << "姓名: " << p.name << endl; cout << "年龄: " << p.age << endl; cout << "工资: " << p.salary; }
输出结果
输入姓名: Bill Jobs 输入年龄: 55 输入工资: 34233.4 显示信息 姓名: Bill Jobs 年龄: 55 工资: 34233.4
在这个程序中,要求用户在main()函数中输入一个人的姓名、年龄和工资。
然后,使用将结构变量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; La variabile di struttura p viene passata alla funzione getData(), che riceve l'input dall'utente e poi lo restituisce alla funzione principale (main). displayData(p); return 0; } Person getData(Person p) { cout << "输入姓名: "; cin.get(p.name, 50); cout << "输入年龄: "; cin >> p.age; cout << "输入工资: "; cin >> p.salary; return p; } void displayData(Person p) { cout << "\n显示信息" << endl; cout << "姓名: " << p.name << endl; cout << "年龄: " << p.age << endl; cout << "工资: " << p.salary; }
}
Il risultato di output di questo programma è lo stesso del programma sopra.
In questo programma, la variabile di struttura di tipo Person p viene definita nella funzione main().
La variabile di struttura p viene passata alla funzione getData(), che riceve l'input dall'utente e poi lo restituisce alla funzione principale (main).
p = getData(p);Attenzione:Se i tipi delle due variabili di struttura sono gli stessi, è possibile utilizzare l'operatore di assegnazione)(=
Poi passare la variabile di struttura p alla funzione displayData(), che visualizza le informazioni.