C++: namespaces, default arguments, function overloading, references, inline functions

insert image description here

Personal homepage: Personal homepage
Personal column: "Data Structure" "C Language" "C++"


foreword

This blog serves as a summary of C++ knowledge. Let's get to know namespaces, default parameters, function overloading, references, and inline functions.


1. Namespace

Then when introducing the namespace, we first print "hello world" in C++.

#include <iostream>
using namespace std;

int main()
{
    
    
	cout << "hello world" << endl;

	return 0;
}

Among them, using namespace std; is the use of a namespace.


In C++, there are a large number of variables, functions, and classes to be learned later. The names of these variables, functions, and classes exist in the global scope, which may cause naming conflicts. The purpose of using the namespace is to identify Localize the name of the symbol to avoid naming conflicts or naming pollution. The appearance of the namespace keyword is aimed at this kind of problem.

For example: in C, when we define the variable time, we include the header file <time.h>, which will cause a naming conflict. But in C++, we can avoid this by defining the variable time in a namespace.
insert image description here
This will cause the compiler to issue error C2063: 'time': is not a function warning.
insert image description here

Namespace definition

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.
Variables, functions, and types can be defined in the namespace

namespace test
{
    
    
	//变量
	int time = 0;

	//函数
	int Add(int left, int right)
	{
    
    
		return left + right;
	}
	
	//类型
	struct Stu
	{
    
    
		char name[20];
		char sex[5];
		int age;
	};
}

Namespaces can be defined nested

namespace test
{
    
    
	int time = 0;

	int Add(int left, int right)
	{
    
    
		return left + right;
	}

	struct Stu
	{
    
    
		char name[20];
		char sex[5];
		int age;
	};

	//嵌套定义test1命名空间
	namespace test1
	{
    
    
		int time1 = 1;

		int sub(int a, int b)
		{
    
    
			return a - b;
		}
	}
}

Multiple identical namespaces are allowed to be defined in a project, and the compiler will merge multiple identical namespaces into one

insert image description here

insert image description here

Use of namespaces

  • namespace name and scope qualifier ( :: )
#include <iostream>
using namespace std;

namespace test
{
    
    
	int time = 0;

	int Add(int left, int right)
	{
    
    
		return left + right;
	}

	struct Stu
	{
    
    
		char name[20];
		char sex[5];
		int age;
	};

}

int main()
{
    
    
	cout << test::time << endl;

	cout << test::Add(1, 2) << endl;

	struct test::Stu s;
	return 0;
}

  • Use using to introduce a member in the namespace (partially introduced)
#include <iostream>
using namespace std;

namespace test
{
    
    
	int time = 0;
	int a = 10;

	int Add(int left, int right)
	{
    
    
		return left + right;
	}

	struct Stu
	{
    
    
		char name[20];
		char sex[5];
		int age;
	};

}

using test::Add;
using test::a;

int main()
{
    
    
	//此处time是函数名,表示函数的地址 
	//不能using test :: time 会造成冲突,time变量只能test::time访问
	cout << time << endl;
	cout << a << endl;
	cout << Add(1, 2) << endl;

	struct test::Stu s;
	return 0;
}

  • Use the using namespace namespace name to import
#include <iostream>
using namespace std;

namespace test
{
    
    
	//全部引入时,time变量与time函数会冲突
	//int time = 0;
	int a = 10;

	int Add(int left, int right)
	{
    
    
		return left + right;
	}

	struct Stu
	{
    
    
		char name[20];
		char sex[5];
		int age;
	};

}

using namespace test;

int main()
{
    
    
	cout << a << endl;
	cout << Add(1, 2) << endl;

	return 0;
}

2. Default parameters

Default parameter concept

The default parameter is to specify a default value (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 will be used.

  • Default parameters cannot appear in both definitions and declarations
  • The default value must be a constant or a global variable

As shown below: the parameter a of the function func is the default parameter.

#include <iostream>
using namespace std;

void func(int a = 10)
{
    
    
	cout << a << endl;
}

int main()
{
    
    
	func();
	func(1);
	
	return 0;
}

The result is as follows:

insert image description here

Classification of default parameters

  • All default parameters
#include <iostream>
using namespace std;

void func(int a = 10, int b = 20, int c = 30)
{
    
    
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;

}

int main()
{
    
    
	func();
	cout << endl;

	func(1);
	cout << endl;

	func(1, 2);
	cout << endl;

	return 0;
}

The result is as follows:

insert image description here

  • semi-default parameter

  • Semi-default parameters must be given sequentially from right to left, and cannot be given in intervals

#include <iostream>
using namespace std;


void func(int a, int b = 1, int c = 2)
{
    
    
	cout << a << endl;
	cout << b << endl;
	cout << c << endl;
}

int main()
{
    
    
	func(0);
	cout << endl;


	func(0, 10);
	cout << endl;

	func(0,10,20);
	cout << endl;

	return 0;
}

insert image description here

3. Function overloading

The concept of function overloading

Function overloading : It is a special case of functions. C++ allows several functions with the same name to declare similar functions in the same scope. The formal parameter lists of these functions with the same name (number of parameters, type, type order) are different , and are often used to deal with Implementing functions is similar to the problem of different data types.

  • If two functions with the same name only have different return values, they do not constitute function overloading.

different parameter types

#include <iostream>
using namespace std;

int Add(int a, int b)
{
    
    
	return a + b;
}

double Add(double a, double b)
{
    
    
	return a + b;
}

int main()
{
    
    
	cout << Add(1, 2) << endl;
	cout << Add(1.1, 2.2) << endl;


	return 0;
}

insert image description here


The number of parameters is different

#include <iostream>
using namespace std;

void func()
{
    
    
	cout << "void func()" << endl;
}

void func(int i, int j)
{
    
    
	cout << "void func(int i, int j)" << endl;
}

//注意无参函数的重载函数,不能有全缺省类型的函数,会造成函数调用的二义性
//void func(int i = 1, int j = 1, int k = 1)
//{
    
    
//	cout << "void func(int i = 1, int j = 1, int k = 1)" << endl;
//}

int main()
{
    
    
	func();
	func(1, 1);

	return 0;
}

insert image description here


Parameter type order is different

#include <iostream>
using namespace std;

void func(int i, double j)
{
    
    
	cout << "void func(int i, double j)" << endl;
}

void func(double i, int j)
{
    
    
	cout << "void func(double i, int j)" << endl;
}

int main()
{
    
    
	func(1, 1.1);
	func(1.1, 1);

	return 0;
}

insert image description here

4. Citation

Reference concept

A reference is not a newly defined variable, but an alias for an existing variable (similar to giving a nickname to a person). The compiler will not open up memory space for the reference variable, and it shares the same space with the variable it refers to. .

type + & + reference object name = reference entity

#include <iostream>
using namespace std;

int main()
{
    
    
	int i = 0;

//定义引用类型
// 类型  & 对象名  引用实体
	int  &  ri  =  i;
	
	cout << &i << endl;
	cout << &ri << endl;
	return 0;
}

insert image description here


citation properties

  • References must be initialized when they are defined
  • A variable can have multiple references
  • Once a reference refers to an entity, it cannot refer to another entity
  • Referenced permissions can be panned, zoomed out, not zoomed in

References must be initialized when they are defined

insert image description here

insert image description here


A variable can have multiple references

#include <iostream>
using namespace std;

int main()
{
    
    
	int i = 0;

	int& ri = i;
	int& rri = i;
	int& rrri = i;

	cout << &i << endl;
	cout << &ri << endl;
	cout << &rri << endl;
	return 0;
}

insert image description here


Once a reference refers to an entity, it cannot refer to another entity

insert image description here
insert image description here


Referenced permissions can be panned, zoomed out, not zoomed in

insert image description here
insert image description here


Referenced usage scenarios

1. As a parameter
The return value of a reference is similar to that of a pointer, and the actual parameter can be directly changed through the formal parameter, but the reference is more comfortable to use.

#include <iostream>
using namespace std;

void swap(int& i, int& j)
{
    
    
	int tmp = i;
	i = j;
	j = tmp;
}

int main()
{
    
    
	int i = 0;
	int j = 10;

	cout << " i = " << i << " j = " << j << endl;
	swap(i, j);
	cout << " i = " << i << " j = " << j << endl;

	return 0;
}

insert image description here


2. Do the return value

  • If the function returns out of the scope of the function, if the return object exists, it can be returned by reference. If it has already returned to the system, it must be returned by value.

As follows: What is the result of (1) , (2) , (3)?

int& Add(int a, int b)
{
    
    
	int c = a + b;

	return c;
}

int main()
{
    
    
	int& ret = Add(1, 2);
	cout << "Add(1,2) = " << ret << endl;// (1)
	Add(3, 4);

	cout << "Add(1,2) = " << ret << endl;// (2)
	cout << "Add(1,2) = " << ret << endl;// (3)

	return 0;
}

insert image description here
Why is this result? Doesn't ret only accept the return value of the function function once?
This is because the life cycle of the variable c is created with the creation of the function stack frame, and destroyed when the stack frame is destroyed (the destruction of the stack frame does not really destroy the space, the value of the C variable space will not change, just esp The pointing to ebp has changed). " Creation and Destruction of Function Stack Frame "
ret also points to the space of variable C, the value of ret is printed for the first time, the value of variable C space remains unchanged, and 3 can be printed. When the Add(3, 4) function is called for the second time, there are no other stack frames on the stack frame of the main function. At this time, the stack frame position of Add(3,4) and the stack frame position of Add(1,2) Same, then the space of variable C pointed to by ret is overwritten by the space of variable C this time, and the value of the variable space becomes 7. When the value of ret is printed for the second time, the value of ret is 7. At this time, cout << "Add(1,2) = " << ret << endl; is also a function call, which will overwrite the space of variable C, so that The space of variable C becomes a random value, so the value of ret printed for the third time is a random value.


The difference between reference and pointer

In the grammatical concept, a reference is an alias, and there is no independent space. But in the underlying implementation, the reference actually has space, because the reference is implemented according to the pointer method.

#include <iostream>
using namespace std;

int main()
{
    
    
	int i = 0;

	int& ri = i;
	int* pi = &i;

	return 0;
}

insert image description here
You can see that references are no different from pointers in terms of underlying implementation.

Is there a difference between a reference and a pointer?

  • A reference conceptually defines an alias for a variable, and a pointer stores the address of a variable.
  • References must be initialized when they are defined, pointers are not required
  • After a reference refers to an entity during initialization, it cannot refer to other entities, and a pointer can point to any entity of the same type at any time
  • There are no NULL references, but there are NULL pointers (nullptr in C++)
  • The meaning is different in sizeof: the reference result is the size of the reference type, and the pointer is always the number of bytes occupied by the address space (4 / 8)
  • A change in the value of the reference means that the value of the referenced entity itself changes, and a change in the value of the pointer points to a different variable
  • Multi-level pointers, no multi-level references
  • There are different ways to access entities. The pointer needs to be dereferenced, and the reference compiler will handle it by itself.
  • References are safer than pointers

5. Inline functions

In C language, sometimes we want to improve program efficiency, and some simple functions will be written in the form of macros to improve program efficiency. But for macro functions, it is not easy to debug and check when it goes wrong. So C++ proposed the concept of inline function for this situation.

A function decorated with inline is called an inline function. When compiling, the C++ compiler will expand it at the place where the inline function is called. There is no overhead of function calling to create a stack frame, and the inline function can replace the macro function.
As follows: After the Add function is modified inline, there is no call instruction when it is called, but it is added directly.

#include <iostream>
using namespace std;

inline int Add(int a, int b)
{
    
    
	return a + b;
}

int main()
{
    
    
	int ret = 0;

	ret = Add(1, 2);
	return 0;
}

insert image description here

characteristic

  • Inline is a way of exchanging space for time. If the compiler treats the function as an inline function, it will replace the function call with the function body during the compilation phase. Defect: it may increase the size of the object file
  • Inline is just a suggestion for the compiler. Different compilers have different implementation mechanisms for inline. The general suggestion is to modify functions that are small in scale, non-recursive, and frequently called with inline, otherwise the compiler may ignore the inline feature.
  • Inline does not recommend separation of declaration and definition. Separation will lead to link errors, because inline is expanded, and there is no function address. In the linking stage, the compiler cannot find the function address based on the symbol table.

Summarize

The above is my summary of namespaces, default parameters, function overloading, references, and inline functions in C++. Thanks for the support! ! !
insert image description here

Guess you like

Origin blog.csdn.net/li209779/article/details/132482438