C++入门到理解阶段二基础篇(9)——C++结构体

1.概述

前面咱们已经了解到c++内置了经常使用的数据类型,好比int、long、double等,可是若是咱们要定义一个学生这样的数据类型,c++是没有的,此时就要用到结构体,换言之经过结构体能够帮咱们定义本身的数据类型。ios

2.结构定义和使用

格式 struct 结构体名{//成员列表};c++

好比定义一个学生类型结构体数组

struct Student
{
	string name;
	int age;

};

上面定义好了学生这种数据类型,那如何建立一个Student类型的数据呢?有如下三种方式,推荐一二种app

第一种函数

#include <iostream>
#include <string>
using namespace std;
struct Student
{
	string name;
	int age;

};
int main() {
	//第一种,建立并赋值
	Student s1;
	s1.name = "张三";
	s1.age = 12;
	cout << s1.age << s1.name;
}

第二种spa

#include <iostream>
#include <string>
using namespace std;
struct Student
{
	string name;
	int age;

};
int main() {
	//第二种
	struct Student s1 = {"李四",12};

	cout << s1.age << s1.name;
}

第三种指针

#include <iostream>
#include <string>
using namespace std;
struct Student
{
	string name;
	int age;

}s1;
int main() {
	s1.age = 12;
	s1.name = "lisi";
	cout << s1.age << s1.name;
}

3.结构体数组

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
	string name;
	int age;

};


int main() {
	//2.定义结构体数组
	struct student arr[3] =
	{
		{"aaa",12},
		{"bbb",12},
		{"ccc",12}
	};
	//3.结构体变量赋值
	arr[2].age = 20;
	arr[2].name = "ddd";
	//4.访问结构体数组
	for (int i = 0; i < 3; i++) {
		cout << arr[i].age << arr[i].name <<endl;
	}
}

4.结构体指针

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
	string name;
	int age;

};


int main() {
	
	struct student s = { "lisi",12 };
	//2.定义一个结构体指针
	struct student* p = &s;
	//4.使用结构体指针访问结构体中的属性,须要使用->
	cout << p->age << p->name;
	
}

5.嵌套结构体

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
	string name;
	int id;
};
//2.定义一个嵌套结构体
struct school {
	string name;
	int id;
	struct student s;
};
int main() {
	//3.建立school变量
	school sc = {};
	sc.id = 1;
	sc.name = "清华";
	sc.s.id = 2;
	sc.s.name = "lisi";
	cout << sc.id << sc.name << sc.s.id << sc.s.name << endl;
}

6.结构体做为函数参数传递

第一种做为值传递(不会修改实参)code

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
	string name;
	int id;
};
void p(struct student s);
int main() {
	struct student s = { "lisi",10 };
	p(s);
	cout << "id:" << s.id <<"姓名:"<< s.name<<endl;//id:10姓名:lisi
	return 0;
}
//2.定义一个函数
void p(struct student s) {
	s.id = 100;
	cout << "id:" << s.id <<"姓名:" << s.name << endl;//id:100姓名:lisi
}

 

第二种做为地址传递(会修改实参)blog

#include <iostream>
#include <string>
using namespace std;
struct student
{
	string name;
	int id;
};
void p(struct student *s);
int main() {
	struct student s = { "lisi",10 };
	p(&s);
	cout << "id:" << s.id <<"姓名:"<< s.name<<endl;//id:100姓名:lisi
	return 0;
}
void p(struct student *s) {
	s->id = 100;
	cout << "id:" << s->id <<"姓名:" << s->name << endl;//id:100姓名:lisi
}

注意:ip

//使用地址传递能够避免大量变量赋值占用空间的问题,提升效率,可是会修改实参,如何解决?
void p(const struct student* s) {//使用const修饰以后,对于地址传递,只会读不会修改数据
	//s->id = 100;将不能修改
	cout << "id:" << s->id << "姓名:" << s->name << endl;//id:100姓名:lisi
}



相关文章
相关标签/搜索