C++结构体学习笔记

#include<iostream>
#include<string.h>
using namespace std;

struct date                               //结构体可以定义在函数内,但是不能在函数外调用
{
    int year;
    int month;
    int day;
}X1,X2,X3;                                //在没有typedef时 这个X1,X2,X3表示 例化date X1;  date X2;  date X3;这里表示全局例化 内存开辟在全局区

typedef struct person                      //typedef 起外号 struct person == X
{
    string name;  //一个中文算3个字节
    string sex;
    int year;
    date brithday;                          //结构体内不能内嵌自己 不然就套娃了,无限创建内存占用

    char title[20];

    void display(struct person p)                     //可以将专门输出的函数放在结构体内
    {
        cout<<p.name<<" "<<p.sex<<" "<<p.year<<" "<<p.brithday.year<<" "<<p.brithday.month<<" "<<p.brithday.day<<" "<<p.title<<endl;
    };
    
}X;


void display(struct person p)                          //专门作为结构体 struct person的输出函数
{
    cout<<p.name<<" "<<p.sex<<" "<<p.year<<" "<<p.brithday.year<<" "<<p.brithday.month<<" "<<p.brithday.day<<endl;
};

int main()
{

    sizeof(X);                             
    //结构体所占内存是有字节对齐规律,例如  int + double + char 在结构体的存储方式为 4(4)+8 +1(7)=24;可以改变顺序如4+1(3)+8=16;
    //更改字节对齐方式 在预处理中 #pragma pack(1)//表示字节对齐按照1字节对齐,无额外空间非常紧凑。对齐值就是基础类型字节大小;
    //对于非浮点型(没有小数)的成员变量可以通过位域来优化结构体占内存的方式例如:  int a:1;char b:1;double c; 其中:1表示在它的数据类型中所占的位数,这个值不能超过它本身的数据类型大小,例子运行下来一共就是9字节大小;
    X p;
    p.name="张三";
    p.sex="";
    p.year=10;
    p.brithday={11,8,6};
    //p.title="我自己"; //给char数组赋值时会出现错误因为字符串的const形式赋值给非const形式会报错 所以必须用以下形式
    strcpy(p.title,"我自己");
    p.display(p);
    display(p);

    cout<<p.name<<" "<<p.sex<<" "<<p.year<<" "<<p.brithday.year<<" "<<p.brithday.month<<" "<<p.brithday.day<<endl;

    const person p2={"王五","",9,11,2,2,"我的女朋友"};//用const初始化不会报错
    p.display(p2);
    display(p2);
    cout<<p2.name<<" "<<p2.sex<<" "<<p2.year<<endl;

    const person arr[]={{"李四","",11,{11,1,9}},{"赵六","",12,11,1,8}};  //内嵌结构体的大括号可以省略
    
    for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++)
    {
        //cout<<arr[i]<<endl;//结构体数组不能直接输出要依次输出
        display(arr[i]);//有了该结构体的专门的输出函数就可以输出了
        cout<<arr[i].name<<" "<<arr[i].sex<<" "<<arr[i].year<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hyby/p/13399685.html