Review of C++ Basics (Part 1)

Review of C++ Basics (Part 1)

the cover

foreword

I learned a little bit of C++ before, but I haven't used it for a long time. I read the book from the beginning and took brief notes so that I can review and study it later.

keywords and identifiers

C++ identifiers are composed of letters, numbers, and underscores, and must start with a letter or an underscore

The conventions of the program are commonly known as:

  • Object names generally use lowercase letters;

  • Underscores can be used between words or the first letter of each word can be capitalized

The character type char is used to save the corresponding integer value in the basic character set of the machine, that is, the ASCII code value of the character

To access the data in the memory space where an object is located, you need to know the memory address where the memory space is located, which is realized by the name of the object. That is to say, the object name is essentially a mapping of memory addresses.

It is best to provide an initial value when creating an object to complete initialization. Using uninitialized objects is dangerous and may cause serious errors.

const modifier

  • Do not expect the content of the object to change

  • After the const object is created, its value cannot be changed, so the const object must be initialized.

typedef

typedef double price //price 是double的一个类型别名

The using keyword can also declare an alias

using price = double; //price 是double的一个类型别名

The auto keyword is used to automatically deduce the required data type according to the type of the initial value

The address of the memory space where the lvalue is located can be obtained, but the address of the rvalue cannot be obtained.

operator

<<output operator

>>input operator

Increment and Decrement Operators

int i=0;
i++;
++i; //这两个的作用都等同于i=i+1
//但是他们放到表达式中就不同了
int j;
j=i++;//先赋值,再自增,即j=0,i=1了
j=++i; //先自增,再赋值,即j=1,i=1了
//自减运算符类似

Symbolic precedence: logical NOT highest, followed by relational operators, logical AND and logical OR last

Conditional operator ?:Ternary operator

cond?expr1:expr2Judge the cond expression, return expr1 if it is true, and expr2 if it is false

{

} //用花括号括起来的语句是复合语句,构成一个语句块,在块中引入的名字只能在块内可见。

type of data

Composite types: pointers, references, arrays, functions, unions, enumeration types

Quote:

  • Rename the created object, the compiler just binds this alias to the referenced object, and does not copy the content of the object to the reference.

  • It is equivalent to the same piece of memory, but there are many names for this memory. For example, Xiao Ming can also be called Mingming.

    int counter=0;
    int &refCnt =counter; //refCnt引用counter对象的内容
    
  • Rvalue references: Newly introduced in C++11. It is now possible to manipulate rvalue objects, especially temporary objects generated by the compiler

    int i=0;
    int &&rr1=i+1; //右值引用,绑定到一个临时对象,临时对象的生命期得到了延续,续命了。
    

pointer:

  • The memory address of the data is stored, and then the data is accessed through this object. This kind of object specially used to store addresses is called a pointer object.

    int i =100;
    int *ptr=&i; //&在这里是取址符 现在ptr对象里存放的就是i的地址。
    
  • To access the contents of i, you need to use the dereference operator * to achieve

    *ptr=10; //读取对象i的内容
    
  • Avoid using wild pointers. If the pointer object does not have a specific pointing object when it is defined, it needs to be initialized with nullptr.

    {
    int *ptr1 =nullptr; //空指针
    int *ptr;  //野指针
    }
    
  • multilevel pointer

    Storing the address of a pointer object into another pointer object forms a pointer to a pointer

    int i=1, *ptr =&i;
    int **pptr =&ptr; //指向指针的指针,pptr中存储的是ptr的地址,而ptr中存放的是i的地址
    
  • References can be seen as const pointers that support automatic dereference operations

array

  • An array is an ordered collection of finite elements of the same type, and all elements are sequentially stored in a continuous memory space.

    int arr[5] //存储5个整型元素的数组

  • The value in [] must be an integer constant expression greater than 0

    unsigned cnt =10;
    int arr[cnt];  //不能这样定义,cnt并不是常量表达式
    constexpr int sz =10;
    int arr[sz]; //可以
    
  • The character array will automatically add a string terminator '\0' at the end

  • example

    inr arr[5] ={1,2,3,4,5};
    for (auto i:arr){  //auto自动推断数据元素的类型
    	cout<< i<<endl;
    } //这里只能进行读操作,因为i只是一个临时对象,他与数组arr并没有产生实际上的联系,我觉得
    
    //可以进行写操作的例子
    for (auto &i:arr){
    	i=0;
    } //此时i是引用了,相当于arr的别名,映射的地址都是相同的,因此对i赋值,能够修改arr的内容
    
  • Multidimensional Arrays

    int a2d[3][5]; //二维数组 3*5
    
  • pointer to array

    In general, the compiler's operations on arrays are converted into operations on pointers, and the array name is usually converted into the address of the first element of the array

    int arr[] ={1,2,3,4,5};
    int *p =arr; //arr被转换成arr[0]的地址
    int *p =&arr[0]; //与上一句等价
    
    
  • You can use the pointer to access the array, such as moving the pointer position, so as to access other data in the array. But it should be noted that the range of the array cannot be exceeded during the pointer operation, otherwise you will not know where the pointed address is.

vector

  • The container type can store elements of the same type, but supports variable length operations, and the capacity can be dynamically adjusted according to needs.

  • Definition and initialization

    vector<int> v1; //存放整数的空vector
    vector<int> v2={0,1,2}; //存放三个int元素的vector
    
  • vector<int> vi;
    vi.push_back();  //尾部插入一个元素
    vi.pop_back(); //尾部删除一个元素
    vi.clear(); //移除所有元素
    vi.at(1) //访问vi的第二个元素
    
  • iterator

    In order to support random access, there is something called an iterator in the vector, which is usually obtained by means of the member functions begin and end of the container

    vector<int> vi={0,1,2,3};
    auto itb=vi.begin(); //itb指向vi的第一个元素
    auto ite=ci.end(); //ite指向vi的尾后元素
    //itb和ite都是vector<int>::iterator的迭代器类型
    

    Iterators are similar to pointers, and can be dereferenced to obtain the contents of the pointed object.

    for (auto it=vi.begin();it!=vi.end();++it){
    	*it *=2; //每个元素乘2
    	cout<<*it<<endl;
    }
    

enumerated type

  • Unscoped and scoped enumeration types

  • Unscoped enumeration types and scoped enumeration types

    enum color{red,green,blue}; //enum关键字来定义不限定作用域的枚举类型 
    enum class  stoplight{red,green,yellow}; //enum class 来定义限定作用域的枚举类型
    color c =red; //访问color的枚举成员,限定作用域的不能这样访问了
    stoplight b =stoplight::red; //访问限定作用域的枚举类型
    stoplight a =red; //不行
    
    

function

A function definition consists of four parts: return value type, function name, formal parameter list and function body. Errors are divided into syntax errors and logic errors.

int main(){
	return 0;
}

During a function call, the corresponding actual and formal parameter types must match.

Like object names, function names must be declared before use. Unlike function definitions, function declarations only need to describe the return type, name, and parameter types of the function.

int maximum(int a ,int b); //因为声明没有函数体,因此形参名称也是可以省略的
int maximum(int, int);

In general, function or object declarations are placed in header files, and corresponding definitions are placed in source files.

Local Objects and Global Objects

​ Storage cycle: the time an object is stored in memory

storage cycle type Action cycle storage location
automatic storage cycle The definition location is created in memory and released when it goes out of scope the stack
static storage period The object declared by the static keyword always exists during the running of the program global data area
Dynamic Storage Period The object generated by the new operator, delete releases the memory space heap
thread memory cycle The object created by the thread_local keyword starts when the thread it is in is created and is released when the thread ends

Global objects have external linkage and can be accessed in other files

int g_val =10; //g_val在fun.cpp中定义的全局对象,具有外部链接性
extern int g_val; //extern声明可以使得main.cpp也能访问到g_val
static int gs_val=20; //静态对象,在外部访问不了
int main(){
	cout <<g_val+gs_val;
} //输出30

Parameter passing

The interaction between the actual parameter and the formal parameter of the function: one-way value transfer, two-way reference transfer

In one-way value transfer, the formal parameters of the function change without affecting the actual parameters

void Swap(int x,int y){
	int z(x);
	x=y;
	y=z;
}//形参x y交换

int i(4),j(5);
Swap(i,j);
cout<<i<<j<<endl; //实参 i j的内容并没有被改变

The address is passed , and the value of the actual parameter can be changed through the formal parameter.

void Swap(int *x,int *y){
	int z(*x);
	*x=*y;
	*y=z;
}//形参x y所指向的地址的内容交换

int i(4),j(5);
Swap(&i,&j); //取址符
cout<<i<<j<<endl; //实参 i j的内容交换了

Pass by reference , similar to pass by address

void Swap(int &x,int &y){ //引用,即别名
	int z(x);
	x=y;
	y=z;
}//形参x y内容交换

int i(4),j(5);
Swap(i,j); 
cout<<i<<j<<endl; //实参 i j的内容交换了

const parameter

const parameters seem to be widely used in programs

void fun(const int i); //只可以读i,不可写
void fun(const int *i); //可以更改i的指向,但是改不了指向的地址的内容
void fun(const int &i); //只读,不可写

The above value transfer is safe for actual parameters, but it is inefficient for object copy operations with large data; references can avoid copying, but actual parameters are not safe; const reference formal parameters are safe and efficient.

Pass arguments to the main function

//main函数有两个可选的形参
int main(int argc,char*argv[]){

}
//第一个形参argc的值是argv的元素的个数,第二个形参是一个数组,每个元素是指向C风格字符串的指针 
//argv[0]保存的是可执行程序的名字,可选实参从argv[1]开始

function overloading

  • A group of functions with the same name but different parameter lists in the same scope is called an overloaded function

    const int & getMax(const int &a,const int &b){} //这里的值返回的是一个int常量的引用
    const int & getMax(const int &a,const int &b, const int &c){} //重载
    const string & getMax(const string &a,const string &b){} //重载
    

default function

void turnoff(int time =21); //声明的时候给出了默认形参,调用时不提供实参,则采用默认值21

inline function

inline void Swap(int &x,int &y){}; //inline关键字定义内联函数,直接在调用处嵌入内联函数代码,不发生函数调用,不产生函数调用开销,但对编译器只是建议

lambda expression

  • A lambda expression can be understood as a temporary anonymous function, representing a code unit that can be called

    [captures](parameters)-> return type{statements}
    //parameters 、return type 、statements分别代表形参列表、返回值类型和函数体
    //[]代表lambda引导,captures子句指定在同一作用域下lambda主体访问哪些对象以及如何捕获这些对象,可以为空
    
    int divisor=5;
    vector <int > numbers{ 1,2,3,4,5,10,15,20,25,35,45,50);
    for each(numbers,begin(),numbers.end(),[divisor](int y){
    	if(y%divisor==0) //divisor 为外围divisor 的副本
    		cout <<y <<endl;//输出被 divisor整除的元素
    });
    

macro definition

  • The function is to define an identifier to replace a string of characters, which is the macro name

  • #define 宏名 字符串常量
    #define PI 3.1415926
    

kind

  • A class is a user-defined type of data, the basic idea is abstraction and encapsulation

  • A class is a description of the attributes and operations of a thing. For example, for a fraction class, the basic attribute has a numerator and a denominator, and operations include operations such as reducing fractions and calculating fractional values.

    class Fraction{ //Fraction是类名 有两个数据成员和5个成员函数
    	//数据成员
    	int m_fenzi=0; //分子,默认值为0
    	int m_fenmu=1; //分母,默认值为1
    public: //public关键字后的成员时对外公开的,在程序的任何地方都可以访问
    	//成员函数
    	int fenzi() const{return m_fenzi;} //这里在圆括号后面引入const关键字是说明对this指针指向的const对象的数据成员进行写操作是非法的。
    	int fenmu() const{return m_fenmu;}
    	double value() const; //计算分数值
    	void reduce(); //约分
    private: // private 私有成员函数,只能在类的内部使用 
        //值得注意的是,不显式指明成员的访问属性,访问属性默认private
    	int gcd(int x, int y); //计算x和y的最大公约数
    
    }; //类中只有成员函数的声明,定义最好放在类外面
    
    double Fraction::value() const{
    	return static_cast<double> (m_Fenzi)/m_fenmu;
    } //成员函数value 的定义
    
    Fraction a;
    a.value(); 
    a.value(&a); //这两句是等价的,意思是当通过对象调用成员函数时,有一个隐式的指针类型形参this接受了调用对象的地址
    double value(Fraction *const this)const; //value 成员函数的声明自动转换为该形式,一个隐式的指针类型形参this
    

    The struct keyword can also be used to define a class, and the access attribute of the class members in the struct definition is public by default

  • friend function

    Non-public members of a class can be accessed without being a member of the class.

    class Fraction{
    	friend ostream &print(ostream&os, const Fraction &a); //friend关键字声明友元函数
    };
    
  • friend class

     class cricle; //类的前向声明
    class rectangle{
    	friend class cricle; //友元类
    }; 
    //友元都是单向传递的,你是我的朋友,但我不是你的朋友
    
  • Constructors and Destructors

    The initialization process of a class type object is completed by a special class of member functions called constructors

    The constructor helps the object to perform initialization operations for the data members when the object is created, and the constructor will be executed as long as the class type object is created

    Constructor: 1. The function name is consistent with the class name; 2. No return value; 3. Cannot be declared as a const member function

    class Fraction{
    	public:
    		Fraction()=default; //默认构造函数
    		Fraction(int above, int below):m_fenzi(above),m_fenmu(below){} //显示定义构造函数,但是也是默认构造函数
    		Fraction(int above, int below){
    			m_fenzi=above;
    			m_fenmu=below;
    		}//这一个等同于上一个构造函数,但是上一个在m_fenzi和m_fenmu创建时就初始化了,这个还要再赋值一下,上一个执行效率更高。
    };
    

    destructor

    class Fraction{
    	public:
    		~Fraction(){} //析构函数
    };
    
  • Static members : Static members can be declared through the static keyword, but the members are shared, and class objects do not contain static members

    class Fraction{
    	pulic:
    		static int num;
    };
    Fraction a ;//a成员中不包含num这个成员
    

    If you think my writing is good, please give me a free like! If there are errors in the content, please also give me feedback.

Guess you like

Origin blog.csdn.net/qq_45830323/article/details/130130662