黑马程序员匠心之作=结构体

1,结构体定义

2,结构体数组

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

};
int main()
{
	stu stu1[2] = {
		{"张三",18, 90},
		{"李四",18, 90}
	};
	for (int i = 0; i < 2; i++)
	{
		cout << "姓名: " << stu1[i].name << "年龄: " << stu1[i].age << "分数:" << stu1[i].score << endl;
	}
	
		system("pause");
		return 0;
}

3,结构体指针

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

};
int main()
{
	stu stu1 = {"张三",18, 90};
	stu* p = &stu1;
	cout<< "姓名:" << p->name << endl;
	system("pause");
	return 0;
}

当定义一个指向结构体的指针时,注意该指针的类型要与结构体类型相同。当使用指针访问结构体里的元素时,要是用“->”

4,结构体嵌套结构体

注意结构体嵌套结构体时的用法。

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

};
struct teacher
{
	string name;
	int age;
	struct stu stu1;
};
int main()
{
	teacher t;
	t.name = "a";
	t.age = 50;
	t.stu1.age = 20;
	t.stu1.name = "b";
	t.stu1.score = 90;
	cout << "老师姓名:" << t.name << " 老师学生姓名:" << t.stu1.name << endl;
	system("pause");
	return 0;
}

5,结构体做函数的参数

结构体类型的数据传入参数有两种方式:值传递和地址传递;

值传递:不会改变主函数中结构体的值;

地址传递:会改变主函数中结构体的值。

#include <iostream>
using namespace std;
#include<string>
struct student
{
    string name;
    int age;
    int score;
};
void printstu(struct student stu)
{
    stu.age = 18;
    cout << "子函数1姓名:" << stu.name << " 子函数1年龄:" << stu.age << " 子函数1分数:" << stu.score << endl;
}
void printstu2(student *p)
{
    p->age = 18;
    cout << "子函数2姓名:" << p->name << " 子函数2年龄:" << p->age << " 子函数2分数:" << p->score << endl;
}
int main()
{
    student stu;
    stu.name = "hhhh";
    stu.age = 16;
    stu.score = 90;
    printstu(stu);
    cout << "主函数1姓名:" << stu.name << " 主函数1年龄:" << stu.age << " 主函数1分数:" << stu.score << endl;
    printstu2(&stu);
    cout << "主函数2姓名:" << stu.name << " 主函数2年龄:" << stu.age << " 主函数2分数:" << stu.score << endl;
    system("pause");
    return 0;
}

6,结构体中const的使用情景。

传递结构体作为函数参数时,若使用值传递,则传递的时候内存需要复制结构体内所有的值,并且赋值给函数;

若使用指针传递,指针只占用四个字节(32位),则需要的内存大大减少。在函数中误修改原来的值,将指针类型的参数改为const类型。

#include <iostream>
using namespace std;
#include<string>
struct student
{
    string name;
    int age;
    int score;
};

void printstu2(const student *p)
{
    //p->age = 18;//错误操作,const修饰*,此时不能改变指针指向的值;
    cout << "子函数2姓名:" << p->name << " 子函数2年龄:" << p->age << " 子函数2分数:" << p->score << endl;
}
int main()
{
    student stu;
    stu.name = "hhhh";
    stu.age = 16;
    stu.score = 90;
   
    printstu2(&stu);
    cout << "主函数2姓名:" << stu.name << " 主函数2年龄:" << stu.age << " 主函数2分数:" << stu.score << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yyyllla/article/details/109299343