C++学习笔记(1)

基础知识

相比于python等语言,c++是静态类型的,变量的类型在编译时确定,而python在运行时确定。这对于C++编译器来说就必须在编译时知道所有变量的类型。

C++提供了很多内建(builtin)数据类型,运算符及流程控制申明。

C++之所以经久不衰是因为其能允许编程者实现自己的数据类型,并且可以实现很底层的操作。

Built-in Types

类型:定义数据和与之对应的操作

C++内建类型:

  • 算数类型:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
bool 
char //8bits
int //16bits
long //32bits
long long //64bits
float //32bits
double 
long double
short

wchar_t
char16_t
char32_t
  • void类型

1 byte = 8 bits,C++的内存是按byte尺度来管理的,int类型占16 bits,则实际上一个变量占了两个地址单元大小的内存。

变量声明

TYPE NAME = VALUE;声明的同时进行赋值。

extern

使用extern关键字可以在其他文件中使用本文件中定义的变量

1
2
3
4
5
6
//separate complilation
//in file 1
int bank_account_number = 1111;

//in file 2
extern int bank_account_number;

scope

变量找最近的层,尽量不要让local的变量和global的变量重名。

复合类型(compound type)

引用(reference)&

bind to a local variable, 与一个局部变量绑定,绑定的变量发生改变,本变量就改变

不能和字面量(literal)和const绑定:

1
2
3
4
5
6
string& b = "hello"; //❌ bind to a const char *

const int& a = 13; //✔️ 只有这种情况下可以
//实际编译时发生的过程:
    const int temp = 13;
    a = temp;

指针(pointer)

  • 定义指针:

    • TYPE * NAME = ADDRESS_LIKE
  • 解引用的步骤

    • 找到地址
    • 根据地址去获取目标值

指针与引用的区别

引用一定要进行初始化

1
int &referen_variable; //❌ 不知道和什么对象绑定

const

  1. 用const修饰的变量不可在后面的过程中不可改变
  2. 必须要进行初始化(和引用一样)

使用场景:

  • 不想数据被更改
1
const int value = 10;
  • 不想参数传递到函数后被更改
1
void function(const &int argument);

const 与 引用结合

  • 不能将常量绑定到非常量上
1
2
3
4
5
6
7
8
int i = 1;
const int &refi = i;
//non-const(int) bind to const (const int)✔️

const int j = 123;
int &refj = j;
//const(int) bind to non-const (const int)❌ ,why?
refj = 456;//试图改变一个常量的值
  • 引用不一定需要类型匹配
1
2
3
int i = 1;
const int &refi = i;
//(const int) and (int)

const 与 指针结合

top-level const 修饰对象本身

low-level const 修饰基本类型(base type)

从右往左读

1
2
3
4
5
6
// |top-level
const int num = 10;


//|low-level  |top-level
const int * const pointer = #

第二句定义的对象pointer从右往左理解就是:

  1. pointer是一个const对象const pointer
  2. 这个const对象是一个指向int的指针(int *)int * const pointer
  3. 指向的int*是const的const int * const pointer

Type Alias

  • using namespace::object
  • auto
  • decltype
1
2
3
4
5
6
7
#include<iostream>
int function();
int var1 = 10;

using std::cout; //后续只用cout
auto num = function(); //自动推断类型
decltype(var1) var2 = 10; //根据var1的类型定义var2