C++ 结构体

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

结构体是一种复合数据类型,包含不同类型的不同变量。例如,您要存储学生详细信息,例如学生姓名,学生卷数,学生年龄。你有两种方法可以做到这一点,一种方法是为每个数据创建不同的变量,但这种方法的缺点是,如果你想存储多个学生的细节,那么在这种情况下,为每个学生创建单独的一组变量是不可行的。

第二种是通过创建这样的结构来实现它,也是最好的方法:

struct Student{    char stuName[30];    int stuRollNo;    int stuAge;};

现在这三个成员组合起来就像一个单独的变量,你可以像这样创建结构变量:

structure_name variable_name

因此,如果您想要使用此结构保存两名学生的信息,那么您可以这样做:

Student s1, s2;

然后我可以像这样访问Student结构的成员:

//Assigning name to first students1.stuName = "Ajeet";//Assigning age to the second students2.stuAddr = 22;

同样,我可以为每个学生设置并获取结构的其他数据成员的值。让我们看一个完整的例子来把它们放在一起:

C++中的结构示例

#include <iostream>using namespace std;struct Student{   char stuName[30];   int stuRollNo;   int stuAge;};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;   cout<<"Student Record:"<<endl;   cout<<"Name: "<<s.stuName<<endl;   cout<<"Roll No: "<<s.stuRollNo<<endl;   cout<<"Age: "<<s.stuAge;   return 0;}

输出:

Enter Student Name: NeganENter Student Roll No: 4101003Enter Student Age: 22Student Record:Name: NeganRoll No: 4101003Age: 22

相关推荐