[Basic C++] 1. Introduction to introductory knowledge (C++ keywords, namespaces, C++ input & output, default parameters, function overloading)

=========================================================================

Aikanyo gitee own take

C language learning diary: keep working hard (gitee.com)

 =========================================================================

approach period:

[Basic Data Structure] 11. Explanation and Implementation of Merge Sort (Comparison Sort)
(Recursive version + non-recursive version--C language implementation)-CSDN Blog< /span>

 =========================================================================

                     

Introduction: What is C++

  • C language isstructuredand modular< /span> smaller programs suitable for handling , languageFor complex problems, larger programs , When a high degree of abstraction and modeling is required, C language is not suitable a>Object-orientedobject oriented programmingOOP, in the 1980s, the computer industry proposed: solve the software crisis In order to .


    idea , support object-oriented programming language came into being

                             
  • In 1982,Dr. Bjarne Stroustrupbased on C languageIntroduced and expanded the object-oriented concept,
    Invented a new programming language, in order to< /span>C++ is named , Express the origin relationship between the language and the C language
                             
  • Therefore:C++ isbased on the C language ,
    it can carry out procedural programming in C language ,

    You can also carry out object-based programming characterized by abstract data types,
    You can also perform object-oriented programming
                      
  • C++ is based on the C language, Accommodates object-oriented programming ideas,
    and adds many useful libraries, and programming paradigms Etc..
    If you are familiar with C language, it will be helpful to learn C++
                    
  • The main goals of this blog:
    1. Supplement the shortcomings of C language grammar , and C++ is how to optimize the unreasonable design of C language a>,
    For example: Scope aspect, IO aspect, Function aspect, Pointer aspect, Macro aspects, etc.
    2. For subsequent understanding a>Laying the foundationClasses and objects

           

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

Introduction: The Development History of C++

In 1979, Bell LabsBenjani and others were trying to analyze the unix kernel. ,
tried to modularize the kernel , so Extended on the basis of C language, added class mechanism,
Complete a preprocessor that can be run, Call it C with classes

                    

C++ languagealso followstep by step, Yuasa depthtargetprogress

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 members and const member functions
C++3.0 Further improvement, the introduction of templates to solve the ambiguity problems caused by multiple inheritance and the processing of corresponding construction and destruction
C++98 The first version of the C++ standard, most compilers support , and got< /span>Introduced STL (Standard Template Library), rewriting the C++ standard library in a template mannerapproved, American Standards Institute) and ISO (International Organization for Standardization
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 issued a counting report (Technical Report -- TR1), officially renamed C++0x,
that is: planned in the first 10 years of this century Published at some time

C++11 Added many features, Made C++ more like a new language,
Such as: regular expressions, range-based for loops, auto keywords, new containers, list initialization, standard thread library, etc.
C++14 Extensions to C++11, mainly to fix loopholes and improvements in C++11,
such as: generic lambda expressions, auto return value type derivation , binary literal constants, etc.
C++17 Made some minor improvements in C++11 and added 19 new features.
For example: the text information of static_assert() is optional, and the Fold expression is used to Variable templates,
initializers in if and switch statements, etc.
C++20 The largest release since C++11, introduces many new features,
Such as: Modules, Coroutines, Ranges, Concepts (Constraints)
and other major features;
There are alsoupdates to existing features, such as: Lambda supports templates, range for loop supports initialization, etc.
C++23 Under development...

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

              

1. C++ keywords (C++98 version)

C++Total63 keywords, including C 32 keywords for language

The C++ version keyword table:
asm do if return try continue
auto double inline short typedef for
bool dynamic_cast int signed typeid public
break else long sizeof typename throw
case enum mutable static union wchar_t
catch explicit namespace static_cast unsigned default
char export new struct using friend
class extern operator switch virtual register
const false private template void true
const_cast float protected this volatile while
delete goto reinterpret_cast

(The red keywords are keywords that have mentioned or used before in the C language blog )

         

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

2. namespace – namespace keyword

(1). The role of namespace:

currentC/C++medium,change,< /span>target针对这种颮题appearance isnamespace 关键字Last name 污代ornaming conflictevasion, thenProgram name progressing to localization IsName spatial purposeUse. It is possible to lead a multi-strike,intotal areaexistencecapitalnameclasssumfunction,change a little,Massive existencecity coderequired understandingsumfunction


Example:

                     

                     


                    

(2). Definition of namespace:

  • Define namespace, needs to use namespace keyword,

    The keyword is followed bythe name of the namespace, thenAdd a pair of braces {} and you can,

    The content in curly brackets {} is a member of the namespace
                      

  • Ingeneral development, will use the project nameasname of the namespace
                            

Definition of general namespace:

Namespace nested sub-namespace:

Multiple namespaces with the same name exist:
  • The same project is allowed to have multiple namespaces with the same name,
    the compiler will eventually Merge into the same namespace
                 
  • One process in progress test.h(head sentence case text.cpp(C++ sentence item< a i=9>)

                     

                     


                    

(3). Use of namespace:

Define a namespacedefine a new scope,

Everything in the namespace isrestricted to that namespace,

So cannot use the content in the namespace bydirectly calling,

There are three ways to use namespace:

                      

Method 1:
Add namespace name and scope qualifier
  • 作用域限定符两个冒号) --   : :

                       

方式二:
using namespace 命名空间名称 展开命名空间
  • 使用 using namespace 命名空间名称 可以展开对应的命名空间
    展开后可以直接通过该命名空间中成员的名称使用该成员
                        
  • 但是使用该方式对命名空间的展开
    会导致命名空间的所有内容暴露出来
    可能又会导致命名冲突问题
                   
  • 所以一般在自己使用时为了方便才会使用该方式
    如果是项目工程该方式一定要慎重使用,可能会出大问题的

                 

方式三:
使用using关键字只展开命名空间中的某个成员
  • 通过方式二直接展开命名空间会有命名冲突的风险
    那么我们可以通过
    using 命名空间名称::指定成员
    指定只展开命名空间中的某个成员
                         
  • 这种方式比较常用的,
    通常是对一些常用的成员对象进行使用
    避免频繁使用方式一调用命名空间减轻代码冗余

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

三、C++输出&输入

C++中有了新的输入和输出方法,虽然说有了新的输入输出方法,
之前C语言中的输入和输出方法也是可以用的
了解C++的输入和输出方法前,需要先了解以下概念

                     

                     

std -- C++标准库命名空间

stdC++标准库的命名空间名C++标准库的定义实现都放在这个命名空间中
上一标题我们知道了使用命名空间的三种方式,而使用std命名空间的方式要考虑实际情况

               

std命名空间的使用惯例:

  • 在自己的日常练习中,建议直接方式二即可
    即:using namespace std
    这样使用std命名空间就很方便了,不用频繁使用方式一进行操作
                     
  • 而在项目工程中,using namespace std 展开方式二展开),
    标准库就全部暴露出来了,如果我们定义了跟库中重名的 类型/对象/函数
    就会存在命名冲突问题。该问题在日常练习中很少出现
    但是项目开发中代码较多规模大,就很容易出现
                        
  • 所以建议在项目开发中使用方式三指定展开
    即:using std::成员(对象)
    指定展开std命名空间中常用的几个库对象/类型/成员
    像是C++输出时使用的cout输入时使用的cin

                         

                         


                        

cout 和 cin

  • cout  --  console(控制台) out  --  标准输出对象(控制台)  --  流插入
    cin  --  console(控制台) in  --  标准输入对象(键盘)  --  流提取
                        
  • 使用cout标准输出对象cin标准输入对象
    需要包含 <iostream> 头文件IO流头文件以及 按命名空间使用方法使用std
注:C++ <iostream>头文件 不需要像C语言一样加“.h”后缀

早期标准库所有功能全局域中实现声明在“.h”后缀的头文件
使用时只需包含对应头文件即可后来将标准库所有功能实现在std命名空间
为了和C语言头文件区分,也为了正确使用命名空间规定C++头文件不加“.h”后缀
旧编译器(vc 6.0)中还支持 <iostream.h> 格式,后续编译器已不支持,
因此推荐使用 <iostream> + std命名空间 的方式
                   

  • cout cin 全局的流对象endlendline)是特殊的C++符号表示换行输出
    他们都包含在 <iostream>头文件
                         
  • 使用cout进行输出时还需要用到<<  --  流插入运算符
    使用cin进行输入时还需要用到>>  --  流提取运算符
    (在C语言中<<>> 位于算符在C++中又多了以上身份
                    
  • 使用C++输入和输出相对C语言更方便
    不需要像 scanf / printf 输入输出时要手动控制格式%d%p……),
    C++的输入和输出可以自动识别变量类型
                         
  • 实际上 cout cin 分别是 ostream istream 类型对象
    >> <<涉及运算符重载等知识这里只是简单了解并使用
    关于coutcin还有很多更复杂的用法
    比如控制浮点数输出精度控制整型输出进制格式等,但并不常用
    实在需要使用时可以用C语言来操作C++兼容C语言的操作
示例:

对应代码:
//包含IO流头文件:
#include <iostream>

//指定展开命名空间成员:
using std::cout;  //指定展开标准输出对象(控制台)
using std::cin;  //指定展开标准输入对象(键盘)
using std::endl;  //指定展开C++换行符号

int main()
{
	int a = 10; //整型变量
	double b = 3.14; //浮点型变量

	cout << "使用cout打印当前a和b:" << endl;

	//使用cout进行输出:
	cout << a << endl << b << endl;
	/*
	* 通过cout标准输出对象和<<流插入运算符进行输出打印:
	* 
	* 先将a这个变量流进std::cout这个控制台中打印,
	* 再进行endl换行,再将b这个变量
	* 流进std::cout这个控制台中打印,再换行。
	* 
	* 即使 a变量 和 b变量 的类型不同也能打印
	* C++的输入和输出可以自动识别变量类型
	*/
	
	cout << "使用cin分别输入数据到a和b:" << endl;

	//使用cin进行输入:
	cin >> a >> b;
	/*
	* 通过cin标准输入对象和>>流提取运算符对数据进行输入:
	*
	* 让你在控制台上输入的数据分别流入a和b这两个变量中
	*
	* 即使 a变量 和 b变量 的类型不同也能输入
	* C++的输入和输出可以自动识别变量类型
	*/

	cout << "输入后再使用cout进行输出打印:" << endl;

	cout << a << endl << b << endl;

	return 0;
}

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

四、缺省参数

(1). 缺省函数的概念:

缺省参数在声明或定义函数时函数的参数指定一个缺省值
调用该函数时如果没有指定实参则采用该形参的缺省值否则使用指定的实参,

有了缺省参数可以调整参数的各种形式来调用该函数

                        

  • 缺省值必须是常量或者全局变量
                    
  • C语言不支持缺省参数编译器不支持
                             
  • 缺省参数不能在函数声明和定义中同时出现

                     


                    

(2). 缺省函数的分类:

全缺省参数:

函数的所有参数都设置对应的缺省参数

图示:

                          

                   

半缺省参数:

只对函数的部分参数设置对应的缺省参数

                       

  • 半缺省参数必须从右往左依次来给出不能间隔着给
    传参从左往右半缺省参数从右往左
图示:

            

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

             

五、函数重载

自然语言中,一个词可以有多重含义
人们可以通过上下文来判断该词真实的含义,即该词被重载

                           

函数重载的概念:

函数重载是函数的一种特殊情况
C++允许在同一作用域中声明几个功能类似的同名函数
这些同名函数的形参列表参数个数参数类型类型顺序不同
函数重载常被用来处理实现功能类似但数据类型不同的问题

图示:

                     

                     


                    

(难)C++支持函数重载的原理 -- 名字修饰(name Mangling)

为什么C语言不支持函数重载而C++支持函数重载

解决这个问题,需要先了解一下编译链接的过程,往期相关博客:
学C的第三十四天【程序环境和预处理】_高高的胖子的博客-CSDN博客
                        

简单解释编译链接过程:

假设我们现在有三个文件

Func.h                Func.cpp                Test,cpp

函数声明)        (函数实现)        (主函数调用

执行主函数时需要进行以下过程

预处理  =>  编译  =>  汇编  =>  链接

现有文件和其内容:

                     

预处理:
  • 预处理过程操作包括:头文件展开(主要)  /  ​​​宏替换  /  条件编译  /​  去除注释​​​

Fun.cpp文件Test.cpp文件 中,因为都包含了 Func.h头文件

所以在预处理时对头文件进行展开,之后会生成预处理文件Func.i文件 和 Test.i文件

所以在 Func.i文件 中就会有Func函数的声明和实现Func.i函数声明和定义),

Test.i文件会有被调用的函数的声明和调用Test.i函数的声明和实际调用

                           

编译:
  • 编译过程操作包括:检查语法是否错误 / 生成汇编代码

进行编译时生成汇编代码文件.s文件),

Func.s文件Test.s文件分别由 Func.i文件 Test.i文件 生成),

Func.s文件存放了两个重载函数对应的汇编代码

Test.s文件 中则存放了主函数main函数的汇编代码

包括被调用的两个重载函数的汇编代码

要调用这两个重载函数,还需要用到汇编语言中的 call指令获取函数的地址

但在编译阶段,因为 Test.i文件 中只包含了 Func.h头文件只有函数声明没有函数实现

所以 call指令无法获得对应的函数地址

在这种情况下,编译器判断调用的函数和头文件中函数是否匹配,如果匹配的话

即使 call指令 还没找到函数地址也可以先让其通过编译方便实现多文件项目

                  

汇编:
  • 汇编过程操作包括:将汇编代码文件中的代码转换为二进制的机器码
    二级制的机器码CPU能读懂的代码

汇编后生成目标文件.o文件),
 Func.o文件 Test,o文件分别由 Func.s文件Test.s文件 生成),

两个文件都将汇编代码转换成了对应的二进制机器码

                 

链接: 
  • 链接过程操作包括:将目标文件链接合并到一起链接一些没有确定函数地址等等

汇编操作中Func.o文件 Test.o文件 合并为 a.out文件默认情况下),

合并后的 a,out文件 中:

之前在编译过程call指令未找到的函数地址可以在合并后的 a.out文件 中找到
(因为合并前 Func.o文件包含对应函数的实现

                          

                          
---------------------------------------------------------------------------------------------

                       

C++支持重载函数,而C语言不支持的原因:

通过上面对编译链接过程的简单了解,我们可以知道:

编译过程中 call指令 还未找到被调用函数的地址,直到链接过程合并文件后才能够找到

                   

C语言不支持重载函数的原因:

C语言中没有重载函数,即函数名唯一的情况下

找函数地址只需要通过唯一的函数名即可找到
即在链接过程中通过唯一的函数名 Func.o目标文件 中的符号表进行对地址的查找

所以如果C语言中有重载函数函数名不唯一的情况下无法在链接过程中找到函数地址

因此C语言无法支持重载函数

                      

C++支持重载函数的原因 -- 名字修饰(name Mangling):

(Note: different configuration method different ,这りからLinux intermediate g++为例

InC++When there are overloaded functions, that isWhen the function name is not unique,

C++There is a function that canpass the function name and parameter conditions modify a new function name ,

The function name is the same but the parameters are different, then Modify different function names,

then search through the function name modified by Corresponding function address.

  • School name character construction method
    _Z  Function name Number of characters  +  Function name  +  Number of characters
    > Create a single function: Func(int a, double b) ,Function name after modification为:< /span>Similar function name Reason_Z4FuncdiPerson:function after modification Last name, ) int a, double bFunc( If you have one function: _Z4Funcid也可以通过过数况况下创built dissimilar function name

Guess you like

Origin blog.csdn.net/weixin_63176266/article/details/134147231