C++ 结构体和函数

来源:这里教程网 时间:2026-02-16 16:05:02 作者:

之前的教程中,我们了解了结构,即对不同类型的变量进行分组的复合数据类型。在本教程中,我们将学习如何将结构作为参数传递给函数以及如何从函数返回结构。

如何将结构作为参数传递给函数

这里我们有一个函数printStudentInfo(),它将结构Student作为参数,并使用结构变量打印学生的详细信息。这里需要注意的重点是,您应该始终在函数声明之前声明结构,否则您将收到编译错误。

#include <iostream>using namespace std;struct Student{   char stuName[30];   int stuRollNo;   int stuAge;};void printStudentInfo(Student);int main(){   Student s;   cout<<"Enter Student Name: ";   cin.getline(s.stuName, 30);   cout<<"Enter Student Roll No: ";   cin>>s.stuRollNo;   cout<<"Enter Student Age: ";   cin>>s.stuAge;   printStudentInfo(s);   return 0;}void printStudentInfo(Student s){   cout<<"Student Record:"<<endl;   cout<<"Name: "<<s.stuName<<endl;   cout<<"Roll No: "<<s.stuRollNo<<endl;   cout<<"Age: "<<s.stuAge;}

输出:

Enter Student Name: RickEnter Student Roll No: 666123Enter Student Age: 19Student Record:Name: RickRoll No: 666123Age: 19

如何从函数返回结构

在这个例子中,我们有两个函数,一个从用户获取值,将它们赋值给结构成员并返回结构,另一个函数将该结构作为参数并打印细节。

#include <iostream>using namespace std;struct Student{   char stuName[30];   int stuRollNo;   int stuAge;};Student getStudentInfo();void printStudentInfo(Student);int main(){   Student s;   s = getStudentInfo();   printStudentInfo(s);   return 0;}/* This function prompt the user to input student * details, stores them in structure members * and returns the structure */Student getStudentInfo(){   Student s;   cout<<"Enter Student Name: ";   cin.getline(s.stuName, 30);   cout<<"Enter Student Roll No: ";   cin>>s.stuRollNo;   cout<<"Enter Student Age: ";   cin>>s.stuAge;   return s;}void printStudentInfo(Student s){   cout<<"Student Record:"<<endl;   cout<<"Name: "<<s.stuName<<endl;   cout<<"Roll No: "<<s.stuRollNo<<endl;   cout<<"Age: "<<s.stuAge;}

输出:

Enter Student Name: Tyrion lannisterEnter Student Roll No: 333901Enter Student Age: 39Student Record:Name: Tyrion lannisterRoll No: 333901Age: 39

相关推荐