From C language to C++: Introduction to C++ (1)

Friends, guys, we meet again. In this issue, I will explain to you some relevant knowledge points about the C++ language. If it has inspired you after reading it, then please leave your comments and I wish you all the best. It’s done!

C language column: C language: from entry to proficiency

Data Structure Column: Data Structure

Personal homepage: stackY、

 

Table of contents

Foreword:

1. What is C++

2. Development history of C++

3. C++ keywords (C++98) 

4. Namespace

4.1 Namespace definition 

4.2 Use of namespace

4.2.1 Three ways to use namespaces

5.Input, output 

6.Default parameters

6.1 Concept of default parameters

6.2 Classification of default parameters


Foreword:

In all the previous articles, I have used C language to implement various codes. So in this issue, I will use C++ language. So in this issue, let us first understand the basic development of C++ and how C++ compares to C There are some points that need to be paid attention to in language. Without further ado, let’s start directly:

1. What is C++

        C language is a structured and modular language , suitable for handling smaller-scale programs . For complex problems and large-scale programs that require a high degree of abstraction and modeling, C language is not suitable. In order to solve the software crisis, in the 1980s, the computer industry proposed the idea of ​​OOP (object oriented programming: object-oriented) , and programming languages ​​that support object-oriented came into being.
        In 1982, Dr. Bjarne Stroustrup introduced and expanded the object-oriented concept based on the C language and invented a new programming language. In order to express the origin relationship between the language and the C language, it was named C++. Therefore: C++ is based on C language. It can perform procedural programming of C language, object-based programming characterized by abstract data types, and object-oriented programming .

C++ Grandfather: Bjarne Stroustrup

2. Development history of C++

In 1979, when Benjani and others at Bell Labs tried to analyze the Unix kernel, they tried to modularize the kernel , so they introduced C
Based on the language, the class mechanism was added to complete a preprocessing program that can be run, which is called
C with classes。
The development of language is like practicing martial arts, fighting monsters and upgrading. It is also a step-by-step process, from shallow to deep. Let’s first take a look at the historical versions of C++.

 

   stage                                                                   content
C with
classes
Classes and derived classes, public and private members, class construction and destruction, friends, inline functions, assignment operators
Overloading etc.
C++1.0
Add the concept of virtual functions, function and operator overloading, references, constants, etc.
C++2.0
Improved support for object-oriented, new protected members, multiple inheritance, object initialization, abstract classes, static
Stateful members and const member functions
C++3.0
Further improvement, templates are introduced to solve the ambiguity problems caused by multiple inheritance and the corresponding construction and destruction processing.
reason
C++98
The first version of the C++ standard is supported by most compilers and has been approved by the International Organization for Standardization (ISO) and the United States.
Approved by the National Standards Association, the C++ standard library was rewritten in a template manner and STL ( Standard Template Library ) was introduced.
C++03
The second version of the C++ standard has no major changes in language features, mainly: fixing errors and reducing diversity.
C++05
The C++ Standards Committee released a counting report (Technical Report , TR1) and officially changed its name
C++0x , ie: planned to be released sometime in the first decade of this century
C++11
Many features have been added to make C++ more like a new language, such as: regular expressions, range-based for loops
Ring, auto keyword, new container, list initialization, standard thread library, etc.
C++14
The extension to C++11 is mainly to fix loopholes and improvements in C++11 , such as: generic lambda table
Expressions, return value type deduction of auto , binary literal constants, etc.
C++17
Some minor improvements have been made in C++11 , and 19 new features have been added , such as: static_assert() text
This information is optional. Fold expressions are used in variable templates, initializers in if and switch statements, etc.
C++20
The largest release since C ++11 , introducing many new features, such as: Modules , protocols
Major features such as Coroutines, Ranges, and Constraints, as well as support for existing
Feature updates: For example, Lambda supports templates, range for supports initialization, etc.
C++23
formulating _

3. C++ keywords (C++98) 

C++ has a total of 63 keywords and C language has 32 keywords.
Some of the keywords in C++ have been exposed to in the C language stage, so I will not explain too much about the specific keywords. I will explain them in detail in the subsequent study:

4. Namespace

 Before understanding the namespace, we can first take a look at the difference between printing the Hello World! string on the screen and the C++ program and the C language program.

C language program:

//头文件的包含
#include <stdio.h>

//主函数
int main()
{
	//打印函数
	printf("Hello World!\n");

	return 0;
}

C++ program:

//头文件的包含
#include <iostream>

//命名空间的展开
using namespace std;

//主函数
int main()
{
	//打印
	cout << "Hello World!" << endl;
	return 0;
}

1. There are differences in the inclusion of header files between the two.

2. There is an additional namespace in C++

3. There are differences between the two output (printing) functions

Then let’s learn about this magical function in C++: namespace

In C/C++, there are a large number of variables, functions, and classes to be learned later. The names of these variables, functions, and classes will all exist in the global scope, which may cause many conflicts. The purpose of using a namespace is to localize the name of the identifier to avoid naming conflicts or name pollution . The emergence of the namespace keyword is to address this problem.
#include <stdio.h>
#include <stdlib.h>

int rand = 10;

int main()
{
	//C语言没办法解决类似这样的命名冲突问题,所以C++提出了namespace来解决
	printf("%d\n", rand);

	return 0;
}

Such a program will report an error ( error C2365 "rand": redefined; the previous definition was "function"  ), because the variable rand we defined conflicts with the rand name in the library. If we want to solve it, we need to rename it, then Namespace was proposed in C++ to solve this problem.

4.1 Namespace definition 

To define a namespace, you need to use the namespace keyword , followed by the name of the namespace , and then followed by a pair of {} . The {} are the members of the namespace.

1. Normal namespace definition

Variables, functions, and types can be defined in the namespace

//命名空间的名字是任意的,在这里我使用的是我的名字的缩写

// 1. 正常的命名空间定义
namespace ywh
{
	// 命名空间中可以定义变量/函数/类型
	
	//变量
	int rand = 0;
	char ch = 'a';
	int a[10] = { 0 };

	//函数
	int Add(int x, int y)
	{
		return x + y;
	}

	//类型
	struct Node
	{
		int val;
		struct Node* next;
	};
}

 2. Namespaces can be nested

//2. 命名空间可以进行嵌套
//Test.cpp
namespace N1
{
	int a;
	int b;
	int Add(int x, int y)
	{
		return x + y;
	}

	//进行嵌套
	namespace N2
	{
		int c;
		int d;
		int Sub(int x, int y)
		{
			return x - y;
		}
	}
}

3. Allow multiple namespaces with the same name to exist

Header file Test.h

//3. 同一个工程中允许存在多个相同名称的命名空间,编译器最后会合成同一个命名空间中。
//Test.h
namespace N1
{
	int Mul(int x, int y)
	{
		return x * y;
	}
}
Test.h in a project and the two N1s in Test.cpp above will be merged into one
*Notice:
A namespace defines a new scope , and everything in the namespace is limited to that namespace.

4.2 Use of namespace

First of all, it is explained that C++ is compatible with C language, so C language can also be used in C++ compiled documents.

Now that the namespace is defined, how to use it? Look at the code below:

//命名空间的使用
namespace N1
{
	int a = 10;
	int b = 20;
	int Add(int x, int y)
	{
		return x + y;
	}
}

int main()
{
	printf("%d\n", a);
	return 0;
}

This code will report an error when compiling: "a" undeclared identifier. In other words, the compiler does not recognize the namespace we defined ourselves, so what is the correct way to use the namespace?

4.2.1 Three ways to use namespaces

1. Add namespace name and scope qualifier 

There is a knowledge point to use here: the pre-action qualifier "::", its role here is to access the namespace members, use "::" to specify the members in the namespace to be accessed.

//命名空间的使用
namespace N1
{
	int a = 10;
	int b = 20;
	int Add(int x, int y)
	{
		return x + y;
	}
}

int main()
{
	//使用预作用限定符
	printf("%d\n", N1::a);
	return 0;
}

2. Use using to introduce a member of the namespace

namespace N1
{
	int a = 10;
	int b = 20;
	int Add(int x, int y)
	{
		return x + y;
	}
}

//命名空间的使用
//部分展开
using N1::b;

int main()
{
	//使用预作用限定符
	printf("%d\n", N1::a);
	//使用using
	printf("%d\n", b);
	return 0;
}

3. Use using namespace namespace name introduction

namespace N
{
	int a = 1;
	int b = 0;
	int Add(int x, int y)
	{
		return x + y;
	}
}

//全部展开
using namespace N;

int main()
{
	printf("%d\n", b);
	printf("%d\n", Add(10,20));
	return 0;
}

Seeing this we can interpret the first line of C++ code:

using namespace std;

std is the namespace of the C++ standard library. When we expand all std, we can use the standard library directly.

5.Input, output 

 Let’s first take a look at the input and output of C++

#include<iostream>
// std是C++标准库的命名空间名,C++将标准库的定义实现都放到这个命名空间中
using namespace std;

int main()
{
	//输入
	int a = 0;
	cin >> a;

	//输出
	cout << "Hello world!!!" << endl;
	cout << "a = " << a << endl;
	return 0;
}

illustrate:

1. When using the cout standard output object ( console ) and cin standard input object ( keyboard ) , the <iostream> header file must be included
As well as using std by namespace usage .
2. cout and cin are global stream objects , endl is a special C++ symbol, indicating newline output , they are included in the <
iostream> header file.
3.<< is the stream insertion operator, >> is the stream extraction operator.
4. The difference from C language is that the input and output in C++ are operators, while the input and output in C language are functions.
5. It is more convenient to use C++ for input and output. There is no need to manually control the format like printf/scanf input and output.
C++ input and output can automatically identify variable types.
#include <iostream>
using namespace std;
int main()
{
	int a;
	double b;
	char c;

	// 可以自动识别变量的类型
	cin >> a;
	cin >> b >> c;

	//自动识别类型
	cout << a << endl;
	cout << b << " " << c << endl;
	return 0;
}

6.Default parameters

6.1 Concept of default parameters

Default parameters specify a default value for the function's parameters when declaring or defining a function . When calling this function, if no actual parameter is specified, the default value of the formal parameter is used, otherwise the specified actual parameter is used.
//         缺省参数          
void Func(int a = 1)
{
	cout << a << endl;
}
int main()
{
	// 没有传参时,使用参数的默认值
	Func();
	// 传参时,使用指定的实参
	Func(10); 
	return 0;
}

6.2 Classification of default parameters

 1.Complete Ministry

//全缺省参数
void Fun(int a = 10, int b = 20, int c = 30)
{
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << endl;
}

int main()
{
    // 显示传参,从左往右显示传参
	Fun();
    //传一个参数默认只能传给第一个参数
	Fun(1);
	Fun(1, 2);
	Fun(1, 2, 3);
	//是不能这样进行传参的
	//Fun(1, , 3);

	return 0;
}

2. Semi-default parameters

//半缺省参数
//必须从右往左给缺省值
void Fun(int a, int b = 20, int c = 30)
{
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
	cout << endl;
}

int main()
{
	//半缺省不能传空
	Fun(1);
	
	Fun(1, 2);
	Fun(1, 2, 3);

	return 0;
}

Notice:

1. Semi-default parameters must be given sequentially from right to left , and cannot be given at intervals.
2. Default parameters cannot appear in functions and declarations at the same time (given in declarations, not in definitions).
3. The default value must be a constant or a global variable .
4. C language is not supported (the compiler does not support it).

Friends and guys, good times are always short. Our sharing in this issue ends here. Don’t forget to leave your precious three pictures after reading it. Thank you all for your support! 

Guess you like

Origin blog.csdn.net/Yikefore/article/details/133240310