C++:struct学习

1.return一个struct对象的方法
例子:
转载:https://www.cnblogs.com/zplutor/archive/2011/09/25/2190315.html

struct S {
    int Value;
};
 
S GetS(int value) {
 
    S s;
    s.Value = value;
 
    return s;
}
 
int wmain() {
 
    S s = GetS(10);
}

2.结构体作为函数的传入参数时
《1》值传递,形参发生任何改变,不改变实参的值

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

void print_(student s){
	cout << s.name<<"   " << s.age << endl;
	s.name="李4";
}
int main(){
	student s;
	s.name = "lixiao";
	s.age = 10;
	print_(s);
	cout << s.name<<"   " << s.age << endl;
	return 0;
}

运行结果:
在这里插入图片描述
《2》地址传递:形参改变后,实参跟着改变

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

void print_(student *s){
	cout << s->name << "   " << s->age << endl;
	s->name = "李4";
}
int main(){
	student s;
	s.name = "lixiao";
	s.age = 10;
	print_(&s);
	cout << s.name << "   " << s.age << endl;
	return 0;
}

在这里插入图片描述
在传入的结构体参数前加const 表示自函数体内部结构体参数不可修改。会报错
在这里插入图片描述
3. 结构体嵌套,输入,输出案例:

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct student
{
	string name;
	int sorce;
};
struct teacher
{
	string name;
	student student_[5];
};
void fuzhi(teacher Tarray[], int len_tea){
	string str_ = "ABCDE";
	srand((unsigned int)time(NULL));
	for (int i_tea = 0; i_tea < len_tea;i_tea++)
	{
		Tarray[i_tea].name = "teacher_";
		Tarray[i_tea].name += str_[i_tea];
		int num_stu = sizeof(Tarray[i_tea].student_) / sizeof(Tarray[i_tea].student_[0]);
		for (int i_stu = 0; i_stu < num_stu;i_stu++)
		{
			int random_ = rand() % 50+50;
			Tarray[i_tea].student_[i_stu].name = "student_";
			Tarray[i_tea].student_[i_stu].name += str_[i_stu];
			Tarray[i_tea].student_[i_stu].sorce = random_;
		}
	}
}
void print_(teacher tarray[], int len){
	for (int i_tea = 0; i_tea < len;i_tea++)
	{
		cout << "老师姓名: " << tarray[i_tea].name << endl;
		int num_stu = sizeof(tarray[i_tea].student_) / sizeof(tarray[i_tea].student_[0]);
		for (int i_stu = 0; i_stu < num_stu;i_stu++)
		{
			cout << "\t学生姓名:" << tarray[i_tea].student_[i_stu].name <<"  "<<"成绩: "<<tarray[i_tea].student_[i_stu].sorce<< endl;
		}
	}
}
int main(){
	teacher tea[3];
	int len = sizeof(tea) / sizeof(tea[0]);
	fuzhi(tea, len);
	print_(tea, len);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值