结构体

定义结构

为了定义结构,您必须使用 struct 语句。struct 语句定义了一个包含多个成员的新的数据类型,struct 语句的格式如下:

struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;

访问结构成员

为了访问结构的成员,我们使用成员访问运算符(.)
成员访问运算符是结构变量名称和我们要访问的结构成员之间的一个句号
下面的实例演示了结构的用法:

#include <bits/stdc++.h>
using namespace std;
struct N
{
    int a, b;
}c, d;
int main()
{
    cin >> c.a >> c.b >> d.a >> d.b;
    cout << (c.a + c.b) << " " << (d.a * d.b) << endl;
    return 0;
}

结构作为函数参数

您可以把结构作为函数参数,传参方式与其他类型的变量或指针类似。您可以使用上面实例中的方式来访问结构变量:

#include <bits/stdc++.h>
using namespace std;
struct N
{
    int a, b;
}c, d;
void gao(N e, N f)
{
    cout << (e.a + e.b) << " " << (f.a * f.b) << endl;
}
int main()
{
    cin >> c.a >> c.b >> d.a >> d.b;
    gao(c, d);
    return 0;
}
  1. 结构体
    1. 定义结构
    2. 访问结构成员
    3. 结构作为函数参数