您的位置:首页 > 编程语言 > C语言/C++

【C++学习笔记】结构简介

2017-04-03 16:29 387 查看
一、结构简介

1、结构描述

(1)创建一个结构

struct inflatable
{
char name[20];
float volume;
double price;
};


(2)使用一个结构

inflatable hat;
inflatable woopie_cushion;
inflatable mainframe;


C++允许声明时省略struct

(3)使用运算符(.)来访问各个成员

2、结构例子

二、C++结构初始化

1、C++支持将列表初始化用于结构,且等号(=)是可选的。

inflatable duck {"Daphne",0.12,9.98};


2、如果大括号内未包含任何东西,各个成员将被设置为0。

三、结构可以将string类作为成员

         前提只要使用的编译器支持对以string对象作为成员的结构进行初始化。一定要让结构定义能够方位名称空间std。为此,可以将编译指令using移到结构定义之前,也可以将name的类型声明为std::string

#include <string>
struct inflatable
{
std::string name;
float volume;
double price;
};
四、其他结构属性

#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; //设置choice为结构
cout << "bouquet:" << bouquet.name << " for $";
cout << bouquet.price << endl;

choice = bouquet; //将bouquet结构内容赋予choice
cout << "choice: " << choice.name << " for $";
cout << choice.price << endl;
cin.get();
return 0;
}

五、结构数组

1、创建一个结构包含数组

inflatable gifts[100];


2、每个元素都可以使用成员运算符

cin >> gifts[0].volume


要记住,gifts本身是一个数组,而不是结构,因此使用gifts.prices这样的表述是无效的。
#include <iostream>
struct inflatable { char name[20]; float volume; double price; };
int main()
{
using namespace std;
inflatable guests[2] =
{
{"Bambi",0.5,21.99},
{"Godzilla",2000,565.99}
};

cout << "The guests " << guests[0].name << " and " << guests[1].name
<< "\nhave a combined volume of "
<< guests[0].volume + guests[1].volume << " cubic feet.\n";
cin.get();
return 0;
}六、结构中的位字段(以后继续补充,现在理解无能)
C++允许指定占用特定位数的结构成员、字段的类型应为整型或枚举,接下来是冒号,冒号后面是数字,它指定了使用的位数。可以使用没有名称的字段来提供间距。每个成员都被成为位字段(bit field)

struct torgle_register
{
usigned int SN : 4;
usigned int : 4;
bool goodIn : 1;
bool goodTorgle : 1;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: