我们可以像普通数据类型一样,将结构体变量传递给函数,并从函数中返回它。
在 C++ 中将结构体传递给函数
结构体变量可以像任何其他变量一样传递给函数。
考虑这个例子
#include <iostream>
#include <string>
using namespace std;
struct Person {
string first_name;
string last_name;
int age;
float salary;
};
// declare function with
// structure variable type as an argument
void display_data(const Person&);
int main() {
// initialize the structure variable
Person p {"John", "Doe", 22, 145000};
// function call with
// structure variable as an argument
display_data(p);
return 0;
}
void display_data(const Person& p) {
cout << "First Name: " << p.first_name << endl;
cout << "Last Name: " << p.last_name << endl;
cout << "Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
输出
First Name: John Last Name: Doe Age: 22 Salary: 145000
在这个程序中,我们将结构体变量 p 通过引用传递给函数 display_data()
,以显示 p
的成员。
在 C++ 中从函数返回结构体
我们也可以从函数返回一个结构体变量。
让我们看一个例子。
#include <iostream>
#include <string>
using namespace std;
// define structure
struct Person {
string first_name;
string last_name;
int age;
float salary;
};
// declare functions
Person get_data();
void display_data(const Person&);
int main() {
Person p = get_data();
display_data(p);
return 0;
}
// define function to return structure variable
Person get_data() {
Person p;
string first_name;
string last_name;
int age;
float salary;
cout << "Enter first name: ";
cin >> first_name;
cout << "Enter last name: ";
cin >> last_name;
cout << "Enter age: ";
cin >> age;
cout << "Enter salary: ";
cin >> salary;
// return structure variable
return Person{first_name, last_name, age, salary};
}
// define function to take
// structure variable as an argument
void display_data(const Person& p) {
cout << "\nDisplaying Information." << endl;
cout << "First Name: " << p.first_name << endl;
cout << "Last Name: " << p.last_name << endl;
cout << "Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
输出
Enter first name: John Enter last name: Doe Enter age: 22 Enter salary: 145000 Displaying Information. First Name: John Last Name: Doe Age: 22 Salary: 145000
在这个程序中,我们在 get_data()
函数中获取了结构体变量的用户输入,并将其从函数返回
然后我们将结构体变量 p 通过引用传递给 display_data()
函数,该函数显示了信息。
另请阅读