c++ 基础知识-结构体

c++ 基础知识-结构体

1.初始化结构体,结构体数组

#include <iostream>  
#include <string>  
using namespace std;
struct Student
{
	string name;
	int age;
};
int main()
{
	Student stuArr[] = {{"a",1},{"b",2},{"c",3}};
	stuArr[1].name = "d";
	stuArr[1].age = 4;
	for (int i = 0;i<sizeof(stuArr)/sizeof(stuArr[0]);i++)
	{
		cout<<"name :"<<stuArr[i].name
			   <<" "
			   <<"age :"<<stuArr[i].age<<endl;
	}
	return 0;
} 

2.结构体指针

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

struct Student
{
	string name;
	int age;
};
int main()
{
	Student stu;
	stu.name = "a";
	stu.age = 2;
	Student *p = &stu;
	//*p->name = "b";
	//*p->age = 5;
	cout<<"name :"<<p->name<<endl;//注意是p->name 不是*p->name
	cout<<"age :"<<p->age<<endl;
	return 0;
} 

3.结构体嵌套

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

struct Learn
{
	int math;
	int english;
};
struct Student
{
	string name;
	int age;
	struct Learn learn;
};

int main()
{
	Student stu;
	stu.name = "a";
	stu.age = 5;
	//Learn learn;
	stu.learn.english = 10;
	stu.learn.math = 20;
	cout<<stu.learn.english<<endl;
	cout<<stu.learn.math<<endl;
	return 0;
} 

4.结构体作为函数参数

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

struct Student
{
	string name;
	int age;
};

//void CoutStruct(Student stu);//值传递,需要重新开辟空间,浪费内存
void CoutStruct(Student * stu);//指针,节省空间
//void CoutStruct(const Student * stu);//通常加const,保证输入不改变
int main()
{
	Student stu;
	stu.age = 19;
	stu.name = "a";
	Student * p = &stu;
	CoutStruct(p);
	cout<<"age: "<<stu.age<<endl;//值传递,指针(地址)传递输出结果不同,指针操作的是地址,数据改变,值传递数据不改变
	return 0;
} 

//void CoutStruct(Student stu)
//{
//	stu.age = 30;
//	cout<<"age: "<<stu.age<<endl;
//	cout<<"name: "<<stu.name<<endl;
//}

void CoutStruct(Student * stu)
{
	stu->age = 30;
	cout<<"age: "<<stu->age<<endl;
	cout<<"name: "<<stu->name<<endl;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值