[C++]2、复合类型

1.数组

1.1 声明,初始化

short months[12] = {1};

1.2 字符串

处理字符串有两种ios

一种是C语言,C-风格字符串。 另外一种是基于string类库。数组

1.2.1 C-风格字符串

char cat[5] = {'f', 'a', 't', 's', '\0'};

注意: char数组最后应该以空字符结尾,cout打印字符串时,会打印直到遇到空字符为止。安全

更简单的声明方法, 结尾隐式的包含空字符:spa

char cat[] = "fats";

strlen

计算字符数组长度指针

strlen(cat)

getline

#include <iostream>
using namespace std;

int main()
{
    cout << "请输入出生年份:";
    int year;
    cin >> year;

    cout << "请输入姓名:";
    char name[20];

    cin.getline(name, 20);

    cout << "用户" << name << ", 您出生于" << year << "年";
    return 0;

}

存在问题:code

当输入年份后,系统跳过输入姓名。对象

缘由是:生命周期

cin读完年份后,输入队列中留下了回车的换行符。cin.getline时,直接将空行赋值给姓名数组。队列

解决:内存

在调用getline以前,调用一次get(),清空回车。

1.2.2 string类字符串

声明

#include <cstring>

using namespace std;

string name;

1.3 结构

结构用于存储多种类型的数据

#include <cstring>

using namespace std;

//声明
struct student
{
    string name;

    int age;

    string gender;

    union
    {
        long id_num;
        char id_char[10];
    }id;

};


//初始化

student miku =
        {
            "miku",
            18,
            "girl"
        };

1.3.1 共同体,匿名共同体

//共同体
union
{
    long id_num;
    char id_char[10];
}id;


//匿名共同体
union
{
    long id_num;
    char id_char[10];
};

1.4 枚举

枚举量:每一个枚举值都有对应整数值,从0开始

//声明
enum color{
    red,
    orange,
    yellow
};


//初始化
color a = red;

能够根据枚举量取值

color b = color (2);    //b为orange

枚举能够提高为int,值为枚举量

int c = yellow; //c值为2

1.4.1 设置枚举量

在声明枚举时能够对枚举量进行赋值

enum color{
    red = 1,
    orange = 4,
    yellow = 8
};

1.5 指针和自由存储空间

指针: 指针是一个变量,存储的是值的地址。

对一个变量取地址:变量前面加地址操做符(&)

&home
#include <iostream>

int main()
{
    using namespace std;

    int updates = 6;
    int *p_updates;

    p_updates = &updates;

    cout << "Values: update= " << updates << endl;
    cout << "p_update= " << *p_updates << endl;

    *p_updates += 1;

    cout << "after updated" << endl;

    cout << "Values: update= " << updates << endl;
    cout << "p_update= " << *p_updates << endl;

    return 0;

}

update表示一个值, &update表示该值的地址。

p_update表示指针(地址),*p_update表示该地址指向的值。

1.5.1 声明和初始化指针

int *p_updates;

*p_updates = &updates;

特别注意:

必定要在对指针应用解除引用操做符(*)以前,将指针初始化为一个肯定恰当的地址。

int *p_update;
p_update = (int *)0xB13123;
int *pt = new int;
*pt = 12;

当内存耗尽的状况下,new 将返回0。

值为0的指针被称为空值指针。

1.5.2 删除指针

int *ps = new int;
delete ps;

delete只能用来释放new 分配的内存。不过,对空指针使用delete是安全的。

1.5.3 使用new来建立动态数组

int *psome = new int[10];

delete[] psome;

能够使用角标来操做动态数组。

修改指针的值,+1等价于指向第二个元素。

int *psome = new int[10];

psome[0] = 1;
psome[1] = 2;
psome[2] = 3;

cout << psome[0] << ":" << psome[1] << ":" << psome[2];
cout << endl;
cout << *psome << ":" << *(psome+1) << ":" << *(psome+2);

delete[] psome;

1.5.4 堆栈,堆和内存泄漏

若是new操做符在建立变量后,没有调用delete,会使得包含指针的内存因为做用域和对象生命周期的缘由而释放,可是堆上动态分配的变量或结构却还继续存在。致使内存泄漏。

相关文章
相关标签/搜索