《C++ SYNTAX》第4章 结构体

本文详细介绍了C++中结构体的创建、结构体指针的使用、结构体嵌套结构以及结构体作为参数的应用实例。通过实例学习如何定义、初始化和操作复杂的数据结构。

(4.1) 结构体创建

#include<iostream>
#include<string>
using namespace std;

//结构体一般创建在主函数之前
struct Student
{
	//结构体的默认访问权限为公共
    string name;
    int age;
};

int main()
{
    struct Student s1; //struct可以省略
    //第一种初始化方式
    s1.name = "张三";
    s1.age = 18;
    //第二种初始化方式
    Student s2 = {"李四",19};
    system("pause");
    //结构体数组的初始化
    Student sArr[] =  { {"张三",18},{"李四",19},{"王五",20} };
    sArr[2].name = "赵六"; //修改第三个学生的名字
    return 0;
}

(4.2) 结构体指针

结构体指针(或类的对象指针)要用->符号访问成员(或类的对象的属性和行为)。

#include<iostream>
#include<string>
using namespace std;

struct Student
{
    string name;
    int age;
};

int main()
{
    Student s = {"张三",18};
    Student* p = &s;
    cout << "姓名:" << p->name << "\t年龄:" << p->age << endl;
    system("pause");
    return 0;
}

(4.3) 结构体嵌套

#include<iostream>
#include<string>
using namespace std;

struct Student
{
    string name;
    int age;
};
 
struct Teacher
{
    string name;
    int age;
    Student s;
};

int main()
{
    Teacher t = {"王老师",40,{"小明",18}};
    system("pause");
    return 0;
}

(4.4) 结构体参数

#include<iostream>
#include<string>
using namespace std;

struct Student
{
    string name;
    int age;
};

void studentPrint1(Student s) //值传递
{
    s.age = 18;
    cout << "姓名:" << s.name << "\t年龄:" << s.age << endl;
}

void studentPrint2(Student* s) //地址传递
{
    s->age = 19;
    cout << "姓名:" << s->name << "\t年龄:" << s->age << endl;
}

int main()
{
    Student s = {"张三",18};
    studentPrint1(s);
    studentPrint2(&s);
    system("pause");
    return 0;
}

《 C + +   S Y N T A X 》 系 列 博 客 创 作 参 考 资 料 来 源 《C++\ SYNTAX》系列博客创作参考资料来源 C++ SYNTAX

  1. 《黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难》@黑马程序员.https://www.bilibili.com.

博 客 创 作 : A i d e n   L e e 博客创作:Aiden\ Lee Aiden Lee
特别声明:文章仅供学习参考,转载请注明出处,严禁盗用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值