struct

struct:

结构体 用户自己定义的数据类型

struct 数据类型名{参数列表 };

struct student {
	string name;
	int age;
	int score;
};

使用方法:

定义的同时就可以给它赋值

#include"iostream"
using namespace std;
struct student {
	string name;
	int age;
	int score;
};
int main() {
	struct student s1 = { "小王",18,100 };
	cout << s1.age <<" "<< s1.name <<" "<< s1.score << endl;
	system("pause");
	return 0;
}

数组结合:

#include"iostream"
using namespace std;
struct student {
	string name;
	int age;
	int score;
};
int main() {
	struct student arr[3] = { {"小王",18,100}, {"老王",50,60}, {"王阿姨",49,65}};
	for (int i = 0; i < 3; i++)
		cout << arr[i].name<<" "<<arr[i].age<<" "<<arr[i].score << endl;
	system("pause");
	return 0;
}

指针结合:

指针引用    “->”

#include"iostream"
using namespace std;
struct student {
	string name;
	int age;
	int score;
};
int main() {
	struct student s1 = { "小王",18,100 };
	struct student* p;
	p = &s1;

		cout << p->name<<" "<<p->age<<" "<<p->score << endl;
	system("pause");
	return 0;
}

嵌套使用:

#include"iostream"
using namespace std;
#include<string>
struct student {
	string name;
	int age;
	int score;
};
struct teacher {
	string name;
	int id;
	int age;
	student stu;
};
int main() {
	struct teacher s2 = { "miss刘",1255,25,{"小王",18,100} };
	cout << s2.stu.age << endl;
	system("pause");
	return 0;
}

值传递:

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

void printfstudent(struct student s1) {
	cout << s1.name << " " << s1.age << " " << s1.score << endl;
}
int main() {
	struct student s1={"小王",18,100};
	printfstduent(s1);
	system("pause");
	return 0;
}

地址传递:

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

void printfstudent2(struct student* s1) {
	cout << s1->name << " " << s1->age << " " << s1->score << endl;
}
int main() {
	struct student s1={"小王",18,100};
	printfstudent2(&s1);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值