结构体笔记2
发布日期:2021-11-20 10:17:40 浏览次数:13 分类:技术文章

本文共 939 字,大约阅读时间需要 3 分钟。

结构体做函数参数

//将结构体作为参数向函数中传递
//传递方式有两种:1.值传递 2.参数传递

#include "pch.h"#include 
#include
using namespace std;struct student{
string name; int age; int score;};//打印学生信息函数//1.值传递void printstudent1(struct student s){
cout << "姓名" << s.name << "年龄" << s.age << "分数" << s.score << endl;}//2.指针传递void printstudent2(struct student* p)//定义一个指针存传过来的地址{
cout << "姓名" << p->name << "年龄" << p->age << "分数" << p->score << endl;}int main(){
//结构体变量 struct student s; s.name = "aa"; s.age = 18; s.score = 85; struct student* p; printstudent1(s); printstudent2(&s);//传入地址}

结构体中const的使用

作用:用const防止误操作

#include "pch.h"#include 
#include
using namespace std;struct student{
string name; int age; int score;};void printstu(const struct student* s) {
//s->age = 150; //如果指针传递可以修改实参的数值,为了避免误操作,进行const,只可以读,不可以修改。 cout << s->age;}int main(){
struct student s = {
"aa",10,85 }; printstu(&s);}

转载地址:https://blog.csdn.net/weixin_43223362/article/details/102595699 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:内存分区-代码区、全局区、堆区、栈区
下一篇:头文件#include<string>

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年04月17日 03时06分07秒