当前位置:网站首页>Chapter 4 Composite Types-1

Chapter 4 Composite Types-1

2022-08-11 05:46:00 Zinxso

This chapter contains the knowledge:

 数组

 C风格字符串

 string类字符串

 getline()和get()读取字符串

 Hybrid input string and an array of

 结构

 共用体

 枚举

 指针

 关键字new和delete

 动态数组

 动态结构

 自动存储、静态存储、动态存储

 vector和array

This chapter will introduce all of the above compound type,new和deleteAnd how to use them to manage the data.除此,Will also briefly introducestring类——Another deal with string way.

4.1 数组

数组(array)是一种数据格式,能够存储多个同类型的值.
Array declaration must contain three:
 类型(int or double or others…)
 数组名
 元素个数
语法格式:

typeName arrayName[arraySize]
//例如:
short months[12];
int yams[2] = {
    20, 30} 

arraySizeFor a given number of elements,Must be plastic constant orconstValue or a constant expression(8*sizeof(int)),不能为变量.
注意:编译器不会检查使用的下标是否有效,If a value is assigned to nonexistent elementmonths[110],Pointed out the mistake the compiler will not,但是程序运行后,The assignment may cause problems,Destroy data or code,也可能导致程序异常终止.So must ensure that the program USES the value of an effective.

4.1.2 数组的初始化规则

1、 Initialize the array can only be defined when used,Cannot be directly assigned to another array an array;

int cards = {
    2, 3, 5};   //allowed
int hand[3];    // allowed
hand[3] = {
    2, 3, 5};   //not allowed
hand = cards;      //not allowed

2、初始化数组时,Provide values can be less than the number of elements in the array(Other elements of the default setting is0);
3、In the initialization time[]为空,C++编译器会自动计算元素个数.编译器将使hand数组包含3个元素.(不推荐)

int hand[] = {
    2, 3, 5};

4.1.3 C++数组初始化方法

C++11The curly braces initialization(列表初始化)作为一种通用初始化方式,可用于所有类型.
1、 初始化数组时,可省略“ = ”;

int hand [3] {
    2, 3, 5};

2、 Within the braces can be empty,Will set all the elements to0;
3、Ban narrowing conversion.

long plif[] = {
    24, 93, 3.0};     //not allowed,Floating point number into plastic as narrow
char slifs[4] {
    ‘h’, ‘i’, 1122011, ‘\0};    //not allowed,1122011//超出了char变量的取值范围(假设char变量长度为8位)
char tlifs[4] {
    ‘h’, ‘i’, 112, ‘\0};     // allowed,112在charWithin the scope of variable

4.2 字符串

字符串是存储在内存的连续字节中的一系列字符.
C++There are two kinds of string processing ways:

  1. C-风格字符串(c-style string)
  2. 基于string类库
    C-Style string with empty character(\0)结尾,其ASCII码为0,用来标记字符串的结尾.
char dog[2] = {
    ‘a’, ‘b’ };   //not a string
char dog[2] = {
    ‘a’, ‘\0};  // a string

字符串常量:Just use a string in quotes can be initialized character array to a string.

char bird[11] = {
    “Mr.Cheeps”};

String enclosed in double quotation marks implicitly included at the end of the null character.
注意:字符串常量(双引号)和字符常量(单引号)不能互换.

char shirt = ‘S’;        //ok
char shirt = “S”;      //illegal,”S”表示两个字符(S和\0),Actually said string location

4.3 string类简介

使用string类,必须包含头文件string,string类位于名称空间std中.

#include <string>
using namespace std;

使用stringObject mode and use the same character array:
 可使用C-风格字符串来初始化string对象
 可使用cinTo read the keyboard input to storestring对象,cout显示对象
 You can use array notation to accessstring对象中的字符
stringThe primary difference between objects and character array:可以将stringObject declarations for simple variable rather than an array.

string str1;
string str2 = “dog”;

Class design makes the program can automatically handlestring的大小,Such as the initialization of length0的stringObject according to the programstringObject assignment operation automatically adjust its length.

4.3.2 赋值、拼接和附加

C-风格字符串,头文件cstring提供函数,比如strcpy();
StringClasses can be directly to astring对象赋值给另一个string对象;可使用运算符+=将字符串附加到string对象的末尾,Or straight street through=判断相等.

4.4 结构简介

Structure is a more flexible than the array data format,可以存储多种类型的数据.
Structure when the user defined type,Define the type of data structure declaration properties.Create structure including2步:1)定义结构描述-描述并标记能够存储在结构中的各种数据类型;2)按描述创建结构变量.
例如:

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

在这里插入图片描述
关键字struct表明,这是一个结构.标识符inflatable是这种数据格式的名称,Is the name of the new type ofinflatable.
创建inflatable变量:

inflatable hat;
hat.price;  //可以使用(.)Members of the operator to access the structure,When the return will definedouble类型
hat.name;  //为一个char数组

4.4.1 在程序中使用结构

The location of the structure of statement:
在这里插入图片描述
Advocate the use of external structure statement.

4.4.2 C++11结构初始化

1、支持列表初始化,且“ = ”为可选项;
2、 如果{}为空,All members of the default Settings for0;
3、Do not allow the narrowing conversion.

4.4.4其他结构属性

1)、 Structure as a parameter to the function can be,也可以让函数返回一个结构;
2、 可以使用赋值运算符“ = ”To assign structure to another same type structure.

4.4.5 结构数组

可以创建元素为结构的数组,方法和创建基本类型数组完全相同.
inflatable结构包含一个数组,You can also create elements asinflatable结构的数组,
inflatable gifts[100]; //一个包含100个inflatable类型的结构

4.5 共用体

共用体(union)是一种数据格式,可以存储不同的数据类型,但只能同时存储其中的一种类型.The difference in the structure can be stored at the same time a variety of data types.

union one4all
{
    
   int int_val;
   long long_val;
   double double_val;
}

//可以使用one4all来存储int、long、double,条件是在不同的时间进行:

one4all pail;
pail.int_val = 15;            //store an int
cout << pail.int_val;          
pail.double_val =1.35;            //store a double, int value is lost
cout << pail.double_val;

上例中,pail开始是int变量,后来是double变量.成员名称标识了变量的容量,But sharing body every time can only store a value,So the length of the length of the largest members.
Can be Shared body to imagine into a grid of drawer,One can only to store an object,The structure as a drawer with multiple grid,Can store a variety of objects at the same time.
共用体的用途:
 Using two or more data items format(但不会同时使用),Use the appropriate can save a space.Such as management of a catalogue,其中一些商品的ID为整数,另一些ID为字符串.

4.6 枚举

enumTool provides a way to create a symbolic constant,可代替const,允许定义新类型,But should be carried out according to the strict restrictions.
例子:

enum spectrum 
{
    
red, orange, yellow, green, blue, violet, indigo, ultraviolet
};        //Members have no type

The above statement to complete two tasks:
 让spectrum成为新类型的名称:spectrum被称为枚举(enumeration),类似structA variable called structure;
 将red、orange、yellow等作为符号常量,对应整数值0-7.These constants are called enumeration quantity(enumerator),为spectrum的可能值.
The default will be an integer value(不能为float)Assign symbolic constant,The first enumeration quantity as0,第二个为1,依次类推.
Define an enumeration type,Can only take definition contains symbolic constant value.如:

spectrum band;    //只有8个可能的值 
band = blue;     //valid,blue is an enumerator
band = 3000;    //invalid,blue is not enumerator

枚举只定义了赋值运算符,No arithmetic operator.
枚举量是整形,可被提升为int类型,但int类型不能自动转换为枚举类型:

int color = blue;    //valid, 
band = 4;     //invalid, int not converted to spectrum
color = 4 + red;    //vaild, red converted to int
band = red + blue; // invalid, 右边为int型,Unable to assign a type ofspectrum的变量band;
band = spectrum(3);  //valid,进行了强制类型转换

Enumeration is used to define the relevant symbolic constant,Rather than a new type.
枚举用途:
 定义switch中的符号常量

4.6.1 设置枚举量的值

Can use the assignment operator explicitly initialize the enumeration quantity value:

enum bit{
    one =1,  two = 2, three = 3, eight =8};

When the value specified must be an integer,Also can only display the value of the initialization of enumeration quantity:

enum bigstep{
    first, seconde = 100, third};

firtst默认为0,Back has not been initialized before enumeration quantity value than the value of the large amount of an enumeration1,因此third为101.
可以创建多个值相同的枚举量.此外,也可以使用long或者long long类型的值.

4.6.2 枚举的取值范围

Enumeration of maximum value corresponding to the minimum amount of2的幂-1,For the scope of ceiling;The lowest value in the enumeration quantity,如果>=0,则下限为0,Otherwise the upper limit value of ways,Plus minus sign.
For example, the above definitionbigstep,最大值为101,对应的最小的2的幂为128,So its up to128-1 = 127;如果最小的枚举量为-6,比它小的、最大的2的幂为8,8-1Plus minus sign is the-7.
(Blogger personally now this part is not very important).

原网站

版权声明
本文为[Zinxso]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110512453862.html