Getting Started with C++: Namespaces, Function Overloading, Default Parameters

Table of contents

One: Namespace

1. The meaning of namespace

2. Definition of Namespace

3. How to use the members in the namespace?

summary

Two: C++ input and output

Three: function overloading

1. Concept

2. Examples

3. Why does C++ support function overloading but C does not?

[1] First look at a piece of C language code

[2] We put the above situation into C++

Four: Default parameters

1. Concept

2. Examples

3. Default parameter classification

【1】All default parameters

【2】Semi-default parameters

4. Notes


One: Namespace

1. The meaning of namespace

①In a large-scale project, there are often many functions, classes, variables, etc. If not restricted, different functions or classes are likely to use the same name, which will cause conflicts .
②In order to solve this problem, C++ introduces the concept of namespace, which can put related functions, classes, variables, etc. under the same namespace, so as to avoid conflicts .
③At the same time, the namespace can also improve the readability and maintainability of the program , which is convenient for locating problems when debugging, for example.

2. Definition of Namespace

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

code:

//命名空间
namespace stu
{
	//命名空间中可以定义变量/函数/类型
	int Add(int x, int y)
	{
		return x + y;
	}

	int goal = 50;

	struct Node
	{
		int data;
		struct Node* next;
	};
	//命名空间可以嵌套定义
	namespace teacher
	{
		//命名空间中可以定义变量/函数/类型
		int Add(int x, int y)
		{
			return x + y;
		}

		int goal = 100;

		struct Node
		{
			int data;
			struct Node* next;
		};
	}
}

 Note: A namespace defines a new scope, and all content in the namespace is limited to that namespace.


3. How to use the members in the namespace?

Add namespace name and scope qualifier

code:

​#include <stdio.h>
//命名空间
namespace stu
{
	//命名空间中可以定义变量/函数/类型
	int Add(int x, int y)
	{
		return x + y;
	}

	int goal = 50;

	struct Node
	{
		int data;
		struct Node* next;
	};
	//命名空间可以嵌套定义
	namespace teacher
	{
		//命名空间中可以定义变量/函数/类型
		int Add(int x, int y)
		{
			return x + y;
		}

		int goal = 100;

		struct Node
		{
			int data;
			struct Node* next;
		};
	}
}
int main()
{
	printf("%d\n", stu::goal);
	printf("%d\n",stu::teacher::goal);
}

​

Use using to introduce a member in the namespace

code:

using stu::goal;
//如果想使用嵌套空间中的goal,可以用using stu::teacher::goal
//但是两个不能同时存在,否则会导致多次声明
int main()
{
	printf("%d\n",goal);
}

③Use the using namespace namespace name to import (equivalent to expanding all namespaces)

code:

using namespace stu;
//想访问嵌套空间的goal,可以using namespace stu::teacher
//但是两个不能同时存在,否则goal不明确
int main()
{
	printf("%d\n",goal);
}

summary

Even some important declarations and definitions in C++ (such as cout related to output) are placed in a namespace. Without expanding the namespace or introducing members, cout can be used as a variable or function name .


②If you want to write a larger project , the above three methods of using members in the namespace
It is very bad to directly introduce the namespace (expansion), and it is easy to cause naming conflicts
(using namespace namespace)

If it does not need to be used frequently, we can use it by adding namespace name and scope qualifier

(namespace::member)

If we only need to use a certain member frequently, we can use using to introduce a single member in the namespace
(using namespace::member)


③Multiple namespaces with the same name can exist, and the compiler will finally combine them into one .

(For example, define two namespaces with the same name, and members in both spaces can be used after expansion)


Two: C++ input and output

code:


illustrate:

① When using cout standard output object (console) and cin standard input object (keyboard), you must include the <iostream> header file and use std according to the namespace usage method .

②This involves the knowledge of classes and objects, operator overloading, IO flow, and function overloading. You only need to have a general impression first, and the follow-up studies will answer the questions here one by one.

      ●cout and cin are global stream objects, and endl is a special C++ symbol, which means newline output, and they are all included in the <iostream> header file.

     ● << is a stream insertion operator, >> is a stream extraction operator.
● It is more convenient      to use C++ for input and output, and does not need to manually control the format like printf/scanf input and output.
     The input and output of C++ can automatically identify the variable type (essentially function overloading)

③In the early standard library, all functions were implemented in the global domain, and declared in the header file with the .h suffix. When using it, only the corresponding header file needs to be included. Later, it was implemented in the std namespace. In order to distinguish it from the C header file, Also in order to use the namespace correctly, it is stipulated that the C++ header file does not contain .h ; the old compiler (vc 6.0) also supports the <iostream.h> format, and the subsequent compilers do not support it, so it is recommended to use the method of <iostream>+std .


Three: function overloading

1. Concept

It is a special case of a function. C++ allows several functions with the same name to be declared in the same scope . The formal parameter lists of these functions with the same name (parameter number or type or type order) are different , and are often used to process data with similar functions. different types of problems.

2. Examples

code:

​#include <iostream>
using namespace std;
函数重载
void fun(int x, int y)
{
	cout << "int x,int y" << endl;
}
void fun(double x, double y)
{
	cout << "double x,double y" << endl;
}
void fun()
{
	cout << "NULL" << endl;
}

int main()
{
	fun(2, 0);
	//参数类型不同
	fun(2.0, 0.0);
	//参数个数不同
	fun();
	return 0;
}

​

Note: Different function return values ​​do not constitute function overloading.


3. Why does C++ support function overloading but C does not?

In fact, the main sentence is: C++ has unique rules for modifying function names.

The formation of a C/C++ program requires preprocessing, compiling, assembling, and linking.

        ① Preprocessing: perform macro replacement, header file expansion, and comment deletion (space replacement).

        ② Compilation: convert the code into assembly code (this stage is mainly responsible for syntax analysis, symbol summary ,

                          lexical analysis, semantic analysis).

        ③Assembly: Convert the assembly code into binary machine instructions and generate a symbol table .

        ④ Link: After the compilation is completed, the corresponding source files will be generated into target files, and the link stage is to convert these target files

                       Make the link (the process is complicated).

We don't need to care much about the implementation details of this process, the key points are symbol summarization and symbol table generation .


[1] First look at a piece of C language code

There is no definition of the Add function in the main.c file, but there is a statement, there is no syntax error, and the compilation can be passed.

The Add.c file contains the specific implementation of the Add function.

After the assembly is completed, the two source files will generate corresponding symbol tables.

The symbol table will be merged during the linking process . There is no definition of the Add function in main.obj (the object file generated after the main.c assembly is completed), but there is in Add.obj, and finally merged into _Add(0x200), The address of the Add function can be found and called.

On the basis of the above, if we define one more function with the same name , the two function addresses in the generated symbol table are valid, and it is impossible to distinguish which one should be called, which will cause a link error.

It is not difficult to find that the C language cannot handle this situation because of the conflict caused by the same symbol name . If we generate different symbol names according to the function parameters when generating the symbol table , can't we solve this situation? ?


[2] We put the above situation into C++

 Through this, I understand that the C language cannot support overloading, because there is no way to distinguish functions with the same name. C ++ is distinguished by function modification rules. As long as the parameters are different, the modified names are different, and overloading is supported .

The return value is not included in the modification rules, so only the return value is different cannot constitute function overloading .


Four: Default parameters

1. Concept

       The default parameter is to specify a default value for the parameter of the function when declaring or defining the function . When calling the function, if no actual parameter is specified, the default value of the formal parameter is adopted, otherwise the specified actual parameter is used .


2. Examples


3. Default parameter classification

【1】All default parameters

【2】Semi-default parameters


4. Notes

①Semi -default parameters must be given sequentially from right to left , and cannot be given alternately

②Default parameters cannot appear in function declaration and definition at the same time, it is recommended that default parameters are only set in the declaration

③The default value must be a constant and a global variable

Guess you like

Origin blog.csdn.net/2301_76269963/article/details/130990304