C++语法(九)结构体

1、结构体的创建 

struct Student{
    string name;
    int age;
}stu3;

int main(){
    // 方法一
    Student stu1;
    stu1.name = "zhang";
    stu1.age = 10;

    // 方法二
    Student stu2 = {"li", 22};

    // 方法三
    stu3.name = "wang";
    stu3.age = 12;
}

2、结构体数组的创建

struct Student{
    string name;
    int age;
};

int main(){
    Student stu[3] = {
        {"zhang", 10},
        {"li", 22}
    };
}

3、结构体的指针

struct Student{
    string name;
    int age;
};

int main(){
    Student stu;
    stu.name = "zhang";
    stu.age = 10;
    
    // 注:指针不管指向什么类型,大小都是4字节
    Student *p = &stu;
    p->name = "li";

    cout << stu.name << endl;
}
上一篇:C# 延迟初始化


下一篇:从 Java 到 Go