C++结构体

结构体:结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

结构体的定义和使用

语法:struct 结构体名 {结构体成员列表};

通过结构体创建变量的三种方式:

1.struct 结构体名 变量名

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
};

int main() {
	struct Student s1;

	s1.name = "张三";//对结构体中的成员赋值

	s1.age = 20;

	system("pause");
    return 0;
}

2.struct 结构体名 变量名 = {成员1值, 成员2值}

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
};

int main() {
	struct Student s1 = {"张三",20};

	system("pause");
    return 0;
}

3.定义结构体时顺便创建变量

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
}s1;

int main() {
	
	s1.name = "张三";

	s1.age = 20;

	system("pause");
    
    return 0;
}

创建结构体变量,可以将struct省略去

结构体数组

将自定义的结构体放入数组中方便维护

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
}s1;

int main() {
	
	struct Student s1[2] = {
		{"张三",20},
		{"李四",30}
	};

	system("pause");
    return 0;
}

结构体指针

作用:通过指针访问结构体中的成员

利用操作符 ->可以通过结构体指针访问结构体的属性

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
}s1;

int main() {
	
	struct Student s1[2] = {
		{"张三",20},
		{"李四",30}
	};

	Student* p = s1;

	cout<<"姓名是:"<<p->name<<"年龄是:" <<p->age<< endl;
	cout << "姓名是:" << p++->name << "年龄是:" << p->age << endl;
	system("pause");
    return 0;
}

结构体嵌套结构体

作用:结构体中的成员可以是另一个结构体

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
};

struct Teacher {
	int number;
	string name;
	struct Student stu;
};

int main() {
	
	Teacher t;
	t.name = "老师";
	t.number = 123456;
	t.stu.name = "张三";
	t.stu.age = 20;

	
	system("pause");
    return 0;
}

结构体做函数参数

作用:将结构体作为参数向函数中传递

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
};
//1.值传递
void printStudent1(Student stu) {
	cout<<stu.name<<" " << stu.age << endl;
}
//2.地址传递
void printStudent2(Student* stu) {
	cout << stu->name<<" " << stu->age << endl;
}
int main() {
	
	Student s;
	s.name = "张三";
	s.age = 20;

	printStudent1(s);
	printStudent2(&s);
	system("pause");
    return 0;
}

结构体中const使用场景

作用:用const来防止误操作

原因:因为在面对大量的数据时,使用值传递会在内存中存在数值的拷贝,这个运用的内存就会增多,但是指针类型的内存是恒定的,所以这个时候适合用指针进行操作,但是用指针修改数据会造成所有的数据都会修改,因此使用const来限制数据被修改。

#include <iostream>
using namespace std;

struct Student {

	string name;

	int age;
};

void printStudent(const Student* stu) {
	//stu->age = 100;//因为运用了const,所以这里的修改将无效
	cout << stu->name<<" " << stu->age << endl;
}
int main() {
	
	Student s;
	s.name = "张三";
	s.age = 20;
    printStudent(&s);
	cout<<s.name<<" " << s.age << endl;


	system("pause");
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值