c++ 8-结构体(指针、外部函数、嵌套、引用方式)code sample

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值