Cpp_part3

Cpp_part3

Charles Lv7

Cpp_part3

1.Constructor and destructor 构造和析构函数

destructor 析构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Engine {};
class Car {
Engine e;
Engine* pe;
};
class Test {
int* p; // handle句柄
int m; // value
public:
Test(int i);
// void clean();
~Test();
};
// Test::Test() {}
// 报错,析构会形成野指针,造成程序崩溃
Test::~Test() {
cout << "destruct" << endl;
delete p;
}
Test::Test(int i) {
cout << "construct" << endl;
p = new int(i);
}
// void Test::clean() {
// delete p;
// }

2.Static 静态变量

static 静态的

Summary

1.static local var 一次构造,最后释放

2.static global function

本文件使用(将函数的可链接范围从默认从全局域限制为文件域)

3.static attribute 本类所有对象的共享内存

4.static method ,可以用本类类名直接调用,但内部不可操作非静态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// static
// 静态局部变量
void fun() {
static int i = 0;
i++;
cout << i << endl;
}
void fun_in_other_file();
extern int g_int;
// 声明 vs 定义
// 对于变量而言,声明和定义的区别是你是否为其分配内存
// 文件声明static只能在自己里面使用
// 全局函数默认携带extern
class Static {
static int i;
int j;

public:
Static(int ai, int aj);
};
Static ::Static(int ai, int aj) {
// i = ai;
// 报错,不允许修改(初始化)全局变量
j = aj;
// j++;
// 报错,无法正常访问
// 静态成员函数无this指针,所以也不能用this指针
}
int Static::i = 100;

3.reference 引用

reference:引用是个安全的指针

1
2
3
4
5
void test01() {
int a = 10;
int& r = a;
cout << r << endl;
}

Main part

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <bits/stdc++.h>
using namespace std;
#define M 100007
#define N 1007
#define INF 0x3f3f3f3f
#define ll long long
#define db double
int main(int argc, char* argv[]) {
// malloc free
// new delete
static int a;
Test t(1); //栈区
// t.clean();
// stack vs. heap
/* int* i = new int;
int* j = new int;
cout << i << endl;
cout << j << endl;
if (1) {
int m;
//结束自动析构
} */
Test* t2 = new Test(3); //堆区

delete t2;
//全局变量在main之前创建,main之后释放
test01();

// 设计模式design pattern

return 0;
}
  • Title: Cpp_part3
  • Author: Charles
  • Created at : 2022-12-28 08:19:33
  • Updated at : 2023-02-09 17:57:07
  • Link: https://charles2530.github.io/2022/12/28/cpp-part3/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments