1.数组

类似Java中的数组

1
2
3
4
unsigned int name[10] = {};
name[1] = 9;
name[3] = 1;
cout << sizeof name / sizeof (int);//获取数组长度

2.字符串

(1)char数组形式:

1
2
3
4
5
char name;
char fish[] = "Bubbles";
size_t len = strlen(fish);
cin >> name;
cout << "name is" << name << endl << "length is" << len;

(2)string形式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string str1 = "father";
char first_data[] = {"Le Chapon Dodu"};
string second_data = {"The Bread Bowl"};

char charr[20] = "jaguar";
string str = charr;

string str3 = str1 + str;

char ca1[20];
char ca2[20] = "jagur";
strcpy(ca1, ca2); //copy ca2 to ca1;
strcat(ca1, "juice"); // add juice to end of ca1
unsigned long len1 = str.size(); // return size
size_t len2 = strlen(ca1); // return size
wchar_t title[] = L"chief";
char16_t names[] = u"felonia";
char32_t car[] = U"Humer";

3.结构属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void test() {
user person1 = {
"haha",
3.2f,
2.5
};
cout << person1.name << endl;

user persons[] = {};
user people[2] = {
{"bami", 1.1f, 1.99},
{"God", 2.3f, 3.5}
};
if (person1.name == "haha"){
//...
}
}

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

4.共用体用法和结构属性相同,但是只能同时存储其中一种类型(int、long、double)

1
2
3
4
5
6
7
8
9
10
11
12
    cout << person1.id_val.id_char; 

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

union id{
long id_num;
char id_char[20];
} id_val;
};

5.enum类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void test_color() {
color band;
band = yellow;
int col = black;
col += 1;

bits mybit = bits(2);
}

enum color {
red, orange, yellow, green, blue, black, purple
};

enum bits { 
one = 1, two = 2, three = 3, four = 4
};

6.指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void point() {
int updates = 6; // 声明变量
int *p_update; // 声明int类型指针
p_update = &updates;//声明指针指向的地址

cout << "updates = " << updates; //6
cout << "*p_update = " << *p_update << endl; //6

cout << "Address = " << &updates << endl; //0x7ffd813aebe4
cout << "Address = " << p_update; //0x7ffd813aebe4

int *pt;
pt = (int *) 0xB8000000;

int *pn = new int; //只能通过指针访问值
int higgens;
int *ps = &higgens; //可通过变量和指针访问
}

7.delete和new

delete只能用来释放new 分配的内存,delete后加上指向内存块的指针。

1
2
3
4
5
6
int *ps = new int;
delete ps;

int *psom = new int [10];
psom[5] = 10;
delete [] psom;

8.指针算数

C++允许将指针和整数相加,加1的结果等于原来的地址值加上指向的对象占用的字节数。

1
2
3
4
5
6
int as[3] = {1,2,3};
int *aw = as;

cout << *aw; //默认取第一个
aw = aw +1; //1
cout << *aw; //2

因为int类型指针加1相当于把地址值增加了8,这使得aw的值为第二个元素的值。

9.存储类型

(1)自动存储:函数内部定义的常规变量使用自动存储空间,称为自动变量。自动变量存储在栈中(后进先出)

(2)静态存储:整个程序执行期间都存在的存储方式。可使用在函数外部定义或者static。

(3)动态存储:new和delete运算符提供了一种比自动变量和静态变量更灵活的方法。管理了一个内存池,称为堆。内存管理更加复杂和灵活。

10.使用vector和array代替数组

1
2
3
4
5
6
7
8
vector<double> ve(8);
vector<int>vi;
ve[2] = 2.4;


array<double ,4> ad = {1.1,2.3,1.4,3.2};
array<int,5>ai{};
ai[2] = 2;

本文地址: http://www.yppcat.top/2019/06/16/C-学习笔记-复合类型/