<> catalogue

* Namespace
* Annotate input and output streams
* Default parameters
* function overloading
* quote
* Inline function
* C++11 New features auto keyword
* C++11 New features range based for loop
* keyword nullptr
<> Namespace ( keyword namespace)

stay C++ We will define many variables by ourselves , Functions and classes , This requires taking various variable names at the same time , Function name and class name . If these variables , The names of functions and classes exist in the global scope , We should deliberately avoid the trouble caused by repeated naming , Avoid naming conflicts or name pollution , It is necessary to strictly manage these defined data types ,namespace It is used to localize and manage various identifier names , Avoid the above troublesome keywords .
The syntax format is namespace namespace name {}
. Braces are used to define variables , Of functions and classes , In that case , Even if there is the same identifier name under other scopes, it will not cause conflicts , If you want to use these names, just indicate the corresponding namespace , Of course, it is the name under the global scope , Don't mention it , This manages the various identifier names we need to use . Let's take a look at the code implementation .
// 1. Common namespace mode namespace N1 { int add(int a, int b) // Here it is N1 Inside definition add function { return
a + b; } } //2. Namespaces can be nested namespace N2 { int a = 5; namespace N3 { int b=10; } }
//3. Same namespace name , Finally, the compiler will synthesize a namespace with the same name namspace N1 { int sub(int a, int b) { return
a-b; } } // Content in namespace to be used , There are the following 3 Methods //1 Namespace name plus scope qualifier int main() { std::cout <<
N2::a + N2::N3::b << std::endl; //cout and endl namely C++ Namespace of std Object name in return 0; }
//2. use using Add namespace and scope qualifier to introduce the required name using std::cout; using std::endl; using N1::sub;
using N2::a; using N2::N3::b; int main() { cout << sub(a, b) << endl;
// The imported name can be used directly return 0; } //3. use using namespace namespace name Expand the entire namespace directly using
namespace std; using namespace N1; using namespace N2; using namespace N2::N3;
int main() { cout << add(a, b) << endl; // Comparison of three methods : The first is to add a scope qualifier to the name every time you use it , The second is
return 0; // The imported name can be used directly , Third, after introducing the entire namespace, all members of the namespace can be used directly }
We usually study C++ For convenience C++ Functions or objects in standard libraries are often preceded by using namespace std;

<> Annotate input and output streams

C++ Standard input in ( keyboard ) And standard output ( Console ) The keywords used are cin and cout, Need to include header file iostream And standard namespaces std, And C Linguistic scanf and
printf
There is a big difference , use cout No need to add data format control, such as %d,%f etc. , It will perform automatic type derivation and output , use cin The data format controller is also not required , Implicit type conversion will also occur when different types are entered on the keyboard .
int main() { int a; double b; cin >> a>>b; cout << a <<" "<<b << endl; return
0; //cin And >> Use together cout And << Use together endl Equivalent to line break \n }
<> Default parameters

C++ There can be default parameters in the parameter list of the function , It means default parameter , When a specific value is given when calling a function to pass parameters, the specific value is used , The default value is used when the actual parameter copy value is not passed .
//1. Full default parameters void myprint1(int a = 2, int b = 5, int c = 10) { cout << a + b + c
<< endl; } //2. Semi default parameter void myprint2(int a, int b = 5, int c = 10) { cout << a +
b + c << endl; } int main() { myprint1() ; myprint1(10); myprint2(5);
myprint2(3, 4, 5); return 0; }

be careful :

*
* Semi default parameters must be given from right to left , You can't give it at intervals
*
* Default parameters cannot appear in function declarations and definitions at the same time
*
* The default value must be a constant or a global variable
* 4. C Language does not support such syntax
<> function overloading

C++ There is the concept of function overloading in , Simply put, it allows you to define functions with the same function name , When calling a function , According to the type of parameters passed in by the function , Different number of parameters , The parameter order is different to distinguish which function of the same name to call . There are three corresponding situations in which function overloading occurs .
void func(int a, double b) { cout << "int and double" << endl; } void func(int a)
// All three functions are named func However, the number of parameters is different between two comparisons , Different parameter types , Different order { cout << "int" << endl; } void
func(double a, int b) { cout << "double int" << endl; } int main() { func(1);
// So call here func The corresponding function will be called according to the function overload rules func(1, 1.5); func(2.5, 1); return 0; }

<> Function overloading mechanism

Program operation needs to undergo pretreatment , compile , Compilation and links . When we call a function, in the link phase , The connector should go to the corresponding symbol table according to the function name to find the entry address of the corresponding function to execute the code ,C The language does not support function overloading because the function name in the symbol table is the function name when the function is defined , and C++ The function name in the symbol table has special function name decoration rules , Based on the original function name , The compiler adds function parameter type information to the modified name , The function name in the last generated symbol table uniquely corresponds to a function entry address . This also explains that the function return type is not a factor causing overloading .

<> quote ( keyword &)

References can be easily understood to alias variables , When we define a variable, we will apply for a space in memory accordingly , We have a name for using this space , It is convenient for us to manipulate the value of this space , Using references gives this space another name , Using another name can also manipulate the value of this space .

Usage of references : type & alias = Reference entity
Note that the reference type must be of the same type as the reference entity
// Referenced properties int main() { int a = 10,t=5; int& b = a; //1. References are initialized when they are defined int& c = a;
//2. A variable can have multiple references , That is, you can take multiple aliases //int& c = t; //3. Reference once an entity is referenced , You can no longer reference other entities cout << &a << "
" << &b << " " << &c << endl; return 0; }

<> Often quoted
int main() { //int& a = 10; // Different types a Is a variable ,10 Is constant const int& a = 10; const int b =
5; //int& c = b; // Different types from b reach c Authority amplification , This is not allowed , int e = 8; const int& h = e;
// from e reach h Variable to constant is the reduction of permission , In this order double d = 3.14; //int& f = d; // type mismatch const int& f = d;
// Implicit type conversion occurs here d yes double type , Generate temporary copy value is int Type has constant properties ,f Is a reference to a temporary copy value return 0; }
<> Usage of references

1. As function parameter
int add(int& a,int& b) { return a+b; }
2. As return type
int& add(int a,int b) { static int c=a+b; return c; }
be careful : If the function returns , Out of function scope , If the returned object has not been returned to the system , You can use reference to return , If it has been returned to the system , You must use value passing to return .

<> The difference between reference and pointer

* References must be initialized when defined , Pointer not required
* After referencing an entity during initialization , You can no longer reference other entities , The pointer can point to any entity of the same type at any time
* No, NULL quote , But there are NULL Pointer
* stay sizeof Different meanings in : The reference result is the size of the reference type , But the pointer is always the number of bytes occupied by the address space (32 Lower occupation of bit platform 4 Bytes )
* Reference self addition means that the referenced entity increases 1, Pointer self addition means that the pointer is offset backward by one type of size
* Multi level pointer , But there is no multi-level reference
* Different ways of accessing entities , Pointer needs to be explicitly dereferenced , Reference the compiler to handle it by itself
* References are relatively safer to use than pointers
<> Efficiency comparison between reference parameter transfer and value parameter transfer and reference return and value return

Both value transfer parameter and value transfer return generate temporary variables and return temporary variables , There are space opening and release operations in the middle , In contrast, there are no such processes as reference passing and return , So using references can improve operation efficiency .

<> Inline function ( keyword inline)

Usage is to add modifiers at the beginning of ordinary function definitions inline, It is used at compile time C++ The compiler will expand where the inline function is called , No function stack overhead , To improve the efficiency of program operation .
inline int maxnum(int a,int b) { return (a>b)?a:b; }
<> Inline function properties

* inline It is a practice of exchanging space for time , Save the cost of calling functions . So the code is very long or has loops / Recursive functions are not suitable to be used as inline functions
* inline It's just a suggestion for the compiler , The compiler automatically optimizes , If defined as inline There is a loop in the function body of / Recursion, etc , Compiler optimization ignores inlining .
* inline Separation of declaration and definition is not recommended , Separation will lead to link errors . because inline Expanded , There will be no function address , The link will not be found .
<>C++11 New features auto keyword

C++11 start auto Is to automatically derive and define data types , Explain with code .
#include<vector> int main() { int a=10; auto b = a; // Define variables b We can deduce that it is int type , Value is 10
double c=3.14; auto d = c; // same d namely double type , value 3.14 cout << typeid(b).name() <<
endl; cout << typeid(d).name() << endl; cout << b << endl; cout << d << endl;
vector<int>v1; for (int i = 1; i < 5; i++) { v1.push_back(i); // Used above auto To derive int
,double And other types are not reflected auto Substantial benefits }
// stay stl There are many types with very long names , Can reflect auto It brings convenience , here v1.begin() The type returned is variable for (auto it = v1.begin();
it != v1.end(); it++)//it The type of is vector<int>::iterator.auto it =
v1.begin() and vector<int>::iterator it = v1.begin() Is equivalent { cout << *it << " "; }
return 0; }

<>auto Detailed rules for use

1. use auto When declaring pointer types ,auto and auto * No difference , But when declaring reference types, you must use auto &
2. When multiple variables are declared on the same line , These variables must be of the same type , Otherwise, the compiler will report an error , Because the compiler actually only deduces the first type , Then use the derived type to define other variables .
int main() { int a = 10; double b = 3.14; //auto c = a, d = b; // It has been defaulted here auto
Type of derivation int, But behind b yes double Cannot assign to d return 0; }
be careful auto Cannot be used as formal parameter derivation type
void func(auto a) // This is not allowed
Cannot be used to define an array
auto arr[ ] ={3,5,7}; // Arrays cannot be defined like this
<>C++11 New features range based for loop

Range for Usage of loops
int main() { int arr[] = { 1,2,3,4,5 }; for (auto e : arr)
// Array name must be passed in , Automatically deduce the number of cycles according to the number of array elements , An element of a single pass array { // Assign to e, Traverse the array in this form . cout << e << " "; }
for (auto& e : arr) // Add a reference character & Each cycle generates different e To reference the elements of the array and manipulate the contents of the array , Here we implement the elements of the array +1 Operation of {
e++; } cout << endl; for (auto e : arr) { cout << e << " "; } return 0; }
be careful
void myprint(int arr[]) { for (auto e : arr)
// Here range for The effect of will fail , Should be arr Must be array name , And here, by passing parameters arr It has degenerated into a pointer , The scope cannot be determined . { cout << e << "
"; } }
<> keyword nullptr

stay C++ About null The defined codes are as follows
#ifndef NULL #ifdef __cplusplus #define NULL 0 // therefore null stay C++ Middle is the equivalent and integer number 0 #else
#define NULL ((void *)0) #endif #endif void func(int) // { cout << "int" <<
endl; } void func(int*) { cout << "int*" << endl; } int main() { func(0);
func(NULL); // We want the parameter to be a null pointer NULL Take the second function, but actually take the first function func((int*)NULL);
// Only cast and parameters are nullptr The second function can only be used when func(nullptr); return 0; }

introduce nullptr Just hope to avoid NULL Pointer or shaping 0 Errors in specific situations caused by confusion of .
be careful

* in use nullptr When the pointer is null , No need to include header files , because nullptr yes C++11 Introduced as a new keyword .
* stay C++11 in ,sizeof(nullptr) And sizeof((void*)0) Same number of bytes .
* To improve the robustness of the code , It is recommended to use it in the subsequent representation of null pointer values nullptr.

Technology
©2019-2020 Toolsou All rights reserved,
Solve in servlet The Chinese output in is a question mark C String function and character function in language MySQL management 35 A small coup optimization Java performance —— Concise article Seven sorting algorithms (java code ) use Ansible Batch deployment SSH Password free login to remote host according to excel generate create Build table SQL sentence Spring Source code series ( sixteen )Spring merge BeanDefinition Principle of Virtual machine installation Linux course What are the common exception classes ?