c++学习笔记——复合数据类型 结构

简介

#include <iostream>
struct  inflatable//struct是结构关键字,标识符inflatable是结构的名称
{
    char name[20];
    float volume;
    double price;
};
//结构声明很重要,一般可分为外部声明(位于main()函数外面,此处便是)和内部声明(放在main()内部),
//外部声明可以被其后的所有函数使用,但内部声明只能被声明所属的函数使用,一般使用外部声明,
//c++不提倡使用外部变量,但提倡使用外部结构声明,外部声明符号常量也通常比较合理。
int main()
{
    using namespace std;
    inflatable guest = //c++允许在声明结构变量时省略关键字struct
    {
        "Glorious Gloria",
        1.88,
        29.99
    };
    //初始化和数组一样,用逗号分割值列表,用花括号括起来,一般每个值各占一行,但也可以将他们全部放在同一行。
    inflatable pal
    {
        "Audacious Arthus",
        3.12,
        32.99
    };

    cout << "Expand your guest list with " << guest.name;
    cout << "and" << pal.name << "!\n";
    return 0;
}
Expand your guest list with Glorious GloriaandAudacious Arthus!

c++11结构初始化

与数组一样,c++也支持将列表初始化用于结构,且等号(=)是可选的:

inflatable duck {'Daphne', 0.12, 9.98}

其次,如果大括号内部不包含任何东西,各个成员都被设置成零。最后,不允许缩窄转化。

其他结构属性

#include <iostream>
struct inflatable
{
    char name[20];
    float volume;
    double price;
};
int main()
{
    using namespace std;
    inflatable bouquet
    {
        "sunflowers",
        0.20,
        12.49
    };
    inflatable choice;
    cout << "bouquet: " <<bouquet.name << " for $ ";
    cout << bouquet.price << endl;

    choice = bouquet;
    //可以使用赋值运算符(=)将结构赋值给另一个同类型的结构,
    //这样的结构中每一个成员都将被设置为另一个结构中相应成员的值,即便成员是数组。
    cout << "choice:  " << choice.name << " for $ ";
    cout << choice.price << endl;
    return 0;
}
bouquet: sunflowers for $ 12.49
choice:  sunflowers for $ 12.49

结构数组

#include <iostream>
struct inflatablt
{
    char name[20];
    float volume;
    double price;
};
int main()
{
    using namespace std;
    inflatablt guests[2] = 
    {
        {"Bambi", 0.5,21.99},
        {"Godzilla",200, 565.99}
    };

    cout << "The guests " << guests[0].name << " and " << guests[0].name
        <<"\nhave a combined volume of "
        << guests[0].volume + guests[1].volume << "cubic feet.\n";
    return 0;

}
The guests Bambi and Bambi
have a combined volume of 200.5cubic feet.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值