#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct student
{
string name;
string sno;
string sex;
string sdept;
string classGrade;
string address;
int age;
string (*generate_sentance)(string name,string classGrade,string address); //每用这个包含函数指针的结构体,一定要声明这结构体内的指针一次。
};
string generate_sentance(string name,string classGrade,string address){ //外部实现该函数内容
return name + '\t' + classGrade + '\t' + address;
}
struct teacher
{
string name;
int age;
string classGrade;
}t00;// 创建结构体的方式一;t00
struct school //结构体嵌套结构体
{
struct student stu;
struct teacher thr;
string schoolName;
};
int main(int argc, char const *argv[])
{
struct teacher t01 = {"zhang",36,"321"}; //创建结构体的方式二,声明结构体并为内部变量赋值,也可以先声明,在指定赋值,如t01.name = ***;
struct teacher t02; // 创建结构体的方式三
struct teacher t03 = {"zhang",39,"321"};
struct teacher * p = &t03;
struct student stu01 = {"li","13147890","boy","computer","class01","China",23};
//string sentance = stu01.generate_sentance(stu01.name,stu01.classGrade,stu01.address); 未声明指针直接使用会报错
struct student* stu02 = (struct student *)malloc(sizeof(struct student)); //动态地分配内存空间
stu02->generate_sentance = generate_sentance; // -> 指针引用其内部变量
string sentance = stu02->generate_sentance(stu01.name,stu01.classGrade,stu01.address);
cout << sentance << endl;
/*
结构体数组
**作用:**将自定义的结构体放入到数组中方便维护
语法:struct 结构体名 数组名[元素个数] = { {} , {} , ... {} }
*/
struct teacher tnn[] = {
{"zhang",36,"321"},
{"wang",56,"76"},
{"dang",65,"23"}
};
struct school sch;
sch.stu = {"li","13147890","boy","computer","class01","China",23};
cout << sch.stu.age << endl;
system("pause");
return 0;
}
c++ 8-结构体(指针、外部函数、嵌套、引用方式)code sample
最新推荐文章于 2023-08-17 18:05:03 发布