C++第八课:结构体

C++第八课:结构体

编码文章call10242025-04-10 20:59:0211A+A-

结构体可以把多种不同的数据类型组合在一起,可以让数据看起来更有条理。

代码示例

#include 
#include 
using namespace std;

//定义结构体
struct student
{
    string name;//名字
    int age;//年龄
    float score;//成绩
};


int main()
{
    //创建结构体变量
    student stu1;//方式1:先声明后赋值
    stu1.name = "张三";
    stu1.age = 18;
    stu1.score = 88.8;
 
    //方式2:声明时直接初始化
    student stu2 = { "李四",20,99.9 };

    //访问结构体成员
    cout << stu1.name << "的年龄是:" << stu1.age << endl;

    //结构体数组
    student cls[3] =
    {
        {"张三",18,20},
        {"李四",18,20},
        {"王五",18,20},
    };
    return 0;
}

总结

  1. 定义结构体:struct 名称 {类型 成员1; 类型 成员2; ...}; (末尾分号!)
  2. 创建变量:结构体名 变量名 或 结构体名 变量名 = {值1, 值2, ...}
  3. 访问成员:变量名.成员名 (点号连接)
  4. 结构体数组:结构体名 数组名[大小] = {{...}, {...}, ...}
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4